babylon.glTFFileLoader.js 176 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569
  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. if (!children) {
  759. continue;
  760. }
  761. foundBone = false;
  762. for (var k = 0; k < children.length; k++) {
  763. if (children[k] === id) {
  764. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  765. foundBone = true;
  766. break;
  767. }
  768. }
  769. if (foundBone) {
  770. break;
  771. }
  772. }
  773. // Create bone
  774. var mat = configureBoneTransformation(node);
  775. if (!parentBone && nodesToRoot.length > 0) {
  776. parentBone = getNodeToRoot(nodesToRoot, id);
  777. if (parentBone) {
  778. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  779. nodesToRootToAdd.push(parentBone);
  780. }
  781. }
  782. }
  783. var bone = new BABYLON.Bone(node.jointName, newSkeleton, parentBone, mat);
  784. bone.id = id;
  785. }
  786. // Polish
  787. var bones = newSkeleton.bones;
  788. newSkeleton.bones = [];
  789. for (var i = 0; i < skins.jointNames.length; i++) {
  790. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  791. if (!jointNode) {
  792. continue;
  793. }
  794. for (var j = 0; j < bones.length; j++) {
  795. if (bones[j].id === jointNode.id) {
  796. newSkeleton.bones.push(bones[j]);
  797. break;
  798. }
  799. }
  800. }
  801. newSkeleton.prepare();
  802. // Finish
  803. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  804. newSkeleton.bones.push(nodesToRootToAdd[i]);
  805. }
  806. return newSkeleton;
  807. };
  808. /**
  809. * Imports a mesh and its geometries
  810. */
  811. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  812. if (!newMesh) {
  813. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  814. newMesh.id = id;
  815. }
  816. if (!node.babylonNode) {
  817. return newMesh;
  818. }
  819. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  820. if (!newMesh.material) {
  821. newMesh.material = multiMat;
  822. }
  823. var vertexData = new BABYLON.VertexData();
  824. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  825. var verticesStarts = [];
  826. var verticesCounts = [];
  827. var indexStarts = [];
  828. var indexCounts = [];
  829. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  830. var meshID = meshes[meshIndex];
  831. var mesh = gltfRuntime.meshes[meshID];
  832. if (!mesh) {
  833. continue;
  834. }
  835. // Positions, normals and UVs
  836. for (var i = 0; i < mesh.primitives.length; i++) {
  837. // Temporary vertex data
  838. var tempVertexData = new BABYLON.VertexData();
  839. var primitive = mesh.primitives[i];
  840. if (primitive.mode !== 4) {
  841. // continue;
  842. }
  843. var attributes = primitive.attributes;
  844. var accessor = null;
  845. var buffer = null;
  846. // Set positions, normal and uvs
  847. for (var semantic in attributes) {
  848. // Link accessor and buffer view
  849. accessor = gltfRuntime.accessors[attributes[semantic]];
  850. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  851. if (semantic === "NORMAL") {
  852. tempVertexData.normals = new Float32Array(buffer.length);
  853. tempVertexData.normals.set(buffer);
  854. }
  855. else if (semantic === "POSITION") {
  856. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  857. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  858. for (var j = 0; j < buffer.length; j += 4) {
  859. tempVertexData.positions[j] = buffer[j];
  860. tempVertexData.positions[j + 1] = buffer[j + 1];
  861. tempVertexData.positions[j + 2] = buffer[j + 2];
  862. }
  863. }
  864. else {
  865. tempVertexData.positions = new Float32Array(buffer.length);
  866. tempVertexData.positions.set(buffer);
  867. }
  868. verticesCounts.push(tempVertexData.positions.length);
  869. }
  870. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  871. var channel = Number(semantic.split("_")[1]);
  872. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  873. var uvs = new Float32Array(buffer.length);
  874. uvs.set(buffer);
  875. normalizeUVs(uvs);
  876. tempVertexData.set(uvs, uvKind);
  877. }
  878. else if (semantic === "JOINT") {
  879. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  880. tempVertexData.matricesIndices.set(buffer);
  881. }
  882. else if (semantic === "WEIGHT") {
  883. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  884. tempVertexData.matricesWeights.set(buffer);
  885. }
  886. else if (semantic === "COLOR") {
  887. tempVertexData.colors = new Float32Array(buffer.length);
  888. tempVertexData.colors.set(buffer);
  889. }
  890. }
  891. // Indices
  892. accessor = gltfRuntime.accessors[primitive.indices];
  893. if (accessor) {
  894. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  895. tempVertexData.indices = new Int32Array(buffer.length);
  896. tempVertexData.indices.set(buffer);
  897. indexCounts.push(tempVertexData.indices.length);
  898. }
  899. else {
  900. // Set indices on the fly
  901. var indices = [];
  902. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  903. indices.push(j);
  904. }
  905. tempVertexData.indices = new Int32Array(indices);
  906. indexCounts.push(tempVertexData.indices.length);
  907. }
  908. vertexData.merge(tempVertexData);
  909. tempVertexData = undefined;
  910. // Sub material
  911. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  912. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  913. // Update vertices start and index start
  914. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  915. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  916. }
  917. }
  918. // Apply geometry
  919. geometry.setAllVerticesData(vertexData, false);
  920. newMesh.computeWorldMatrix(true);
  921. // Apply submeshes
  922. newMesh.subMeshes = [];
  923. var index = 0;
  924. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  925. var meshID = meshes[meshIndex];
  926. var mesh = gltfRuntime.meshes[meshID];
  927. if (!mesh) {
  928. continue;
  929. }
  930. for (var i = 0; i < mesh.primitives.length; i++) {
  931. if (mesh.primitives[i].mode !== 4) {
  932. //continue;
  933. }
  934. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  935. index++;
  936. }
  937. }
  938. // Finish
  939. return newMesh;
  940. };
  941. /**
  942. * Configure node transformation from position, rotation and scaling
  943. */
  944. var configureNode = function (newNode, position, rotation, scaling) {
  945. if (newNode.position) {
  946. newNode.position = position;
  947. }
  948. if (newNode.rotationQuaternion || newNode.rotation) {
  949. newNode.rotationQuaternion = rotation;
  950. }
  951. if (newNode.scaling) {
  952. newNode.scaling = scaling;
  953. }
  954. };
  955. /**
  956. * Configures node from transformation matrix
  957. */
  958. var configureNodeFromMatrix = function (newNode, node, parent) {
  959. if (node.matrix) {
  960. var position = new BABYLON.Vector3(0, 0, 0);
  961. var rotation = new BABYLON.Quaternion();
  962. var scaling = new BABYLON.Vector3(0, 0, 0);
  963. var mat = BABYLON.Matrix.FromArray(node.matrix);
  964. mat.decompose(scaling, rotation, position);
  965. configureNode(newNode, position, rotation, scaling);
  966. }
  967. else {
  968. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  969. }
  970. newNode.computeWorldMatrix(true);
  971. };
  972. /**
  973. * Imports a node
  974. */
  975. var importNode = function (gltfRuntime, node, id, parent) {
  976. var lastNode = null;
  977. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  978. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  979. return null;
  980. }
  981. }
  982. // Meshes
  983. if (node.skin) {
  984. if (node.meshes) {
  985. var skin = gltfRuntime.skins[node.skin];
  986. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  987. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  988. if (newMesh.skeleton === null) {
  989. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  990. if (!skin.babylonSkeleton) {
  991. skin.babylonSkeleton = newMesh.skeleton;
  992. }
  993. }
  994. lastNode = newMesh;
  995. }
  996. }
  997. else if (node.meshes) {
  998. /**
  999. * Improve meshes property
  1000. */
  1001. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  1002. lastNode = newMesh;
  1003. }
  1004. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1005. var light = gltfRuntime.lights[node.light];
  1006. if (light) {
  1007. if (light.type === "ambient") {
  1008. var ambienLight = light[light.type];
  1009. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1010. hemiLight.name = node.name;
  1011. if (ambienLight.color) {
  1012. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  1013. }
  1014. lastNode = hemiLight;
  1015. }
  1016. else if (light.type === "directional") {
  1017. var directionalLight = light[light.type];
  1018. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1019. dirLight.name = node.name;
  1020. if (directionalLight.color) {
  1021. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  1022. }
  1023. lastNode = dirLight;
  1024. }
  1025. else if (light.type === "point") {
  1026. var pointLight = light[light.type];
  1027. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1028. ptLight.name = node.name;
  1029. if (pointLight.color) {
  1030. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  1031. }
  1032. lastNode = ptLight;
  1033. }
  1034. else if (light.type === "spot") {
  1035. var spotLight = light[light.type];
  1036. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  1037. spLight.name = node.name;
  1038. if (spotLight.color) {
  1039. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  1040. }
  1041. if (spotLight.fallOfAngle) {
  1042. spLight.angle = spotLight.fallOfAngle;
  1043. }
  1044. if (spotLight.fallOffExponent) {
  1045. spLight.exponent = spotLight.fallOffExponent;
  1046. }
  1047. lastNode = spLight;
  1048. }
  1049. }
  1050. }
  1051. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1052. var camera = gltfRuntime.cameras[node.camera];
  1053. if (camera) {
  1054. if (camera.type === "orthographic") {
  1055. var orthographicCamera = camera[camera.type];
  1056. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1057. orthoCamera.name = node.name;
  1058. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  1059. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1060. lastNode = orthoCamera;
  1061. }
  1062. else if (camera.type === "perspective") {
  1063. var perspectiveCamera = camera[camera.type];
  1064. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1065. persCamera.name = node.name;
  1066. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1067. if (!perspectiveCamera.aspectRatio) {
  1068. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  1069. }
  1070. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  1071. persCamera.maxZ = perspectiveCamera.zfar;
  1072. persCamera.minZ = perspectiveCamera.znear;
  1073. }
  1074. lastNode = persCamera;
  1075. }
  1076. }
  1077. }
  1078. // Empty node
  1079. if (!node.jointName) {
  1080. if (node.babylonNode) {
  1081. return node.babylonNode;
  1082. }
  1083. else if (lastNode === null) {
  1084. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  1085. node.babylonNode = dummy;
  1086. lastNode = dummy;
  1087. }
  1088. }
  1089. if (lastNode !== null) {
  1090. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  1091. configureNodeFromMatrix(lastNode, node, parent);
  1092. }
  1093. else {
  1094. var translation = node.translation || [0, 0, 0];
  1095. var rotation = node.rotation || [0, 0, 0, 1];
  1096. var scale = node.scale || [1, 1, 1];
  1097. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  1098. }
  1099. lastNode.updateCache(true);
  1100. node.babylonNode = lastNode;
  1101. }
  1102. return lastNode;
  1103. };
  1104. /**
  1105. * Traverses nodes and creates them
  1106. */
  1107. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  1108. var node = gltfRuntime.nodes[id];
  1109. var newNode = null;
  1110. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  1111. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  1112. meshIncluded = true;
  1113. }
  1114. else {
  1115. meshIncluded = false;
  1116. }
  1117. }
  1118. else {
  1119. meshIncluded = true;
  1120. }
  1121. if (!node.jointName && meshIncluded) {
  1122. newNode = importNode(gltfRuntime, node, id, parent);
  1123. if (newNode !== null) {
  1124. newNode.id = id;
  1125. newNode.parent = parent;
  1126. }
  1127. }
  1128. if (node.children) {
  1129. for (var i = 0; i < node.children.length; i++) {
  1130. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  1131. }
  1132. }
  1133. };
  1134. /**
  1135. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  1136. */
  1137. var postLoad = function (gltfRuntime) {
  1138. // Nodes
  1139. var currentScene = gltfRuntime.currentScene;
  1140. if (currentScene) {
  1141. for (var i = 0; i < currentScene.nodes.length; i++) {
  1142. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1143. }
  1144. }
  1145. else {
  1146. for (var thing in gltfRuntime.scenes) {
  1147. currentScene = gltfRuntime.scenes[thing];
  1148. for (var i = 0; i < currentScene.nodes.length; i++) {
  1149. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1150. }
  1151. }
  1152. }
  1153. // Set animations
  1154. loadAnimations(gltfRuntime);
  1155. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  1156. var skeleton = gltfRuntime.scene.skeletons[i];
  1157. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  1158. }
  1159. };
  1160. /**
  1161. * onBind shaderrs callback to set uniforms and matrices
  1162. */
  1163. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  1164. var materialValues = material.values || technique.parameters;
  1165. for (var unif in unTreatedUniforms) {
  1166. var uniform = unTreatedUniforms[unif];
  1167. var type = uniform.type;
  1168. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  1169. if (uniform.semantic && !uniform.source && !uniform.node) {
  1170. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1171. }
  1172. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1173. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  1174. if (source === null) {
  1175. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  1176. }
  1177. if (source === null) {
  1178. continue;
  1179. }
  1180. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1181. }
  1182. }
  1183. else {
  1184. var value = materialValues[technique.uniforms[unif]];
  1185. if (!value) {
  1186. continue;
  1187. }
  1188. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1189. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  1190. if (texture === null || texture === undefined) {
  1191. continue;
  1192. }
  1193. shaderMaterial.getEffect().setTexture(unif, texture);
  1194. }
  1195. else {
  1196. GLTF1.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  1197. }
  1198. }
  1199. }
  1200. onSuccess(shaderMaterial);
  1201. };
  1202. /**
  1203. * Prepare uniforms to send the only one time
  1204. * Loads the appropriate textures
  1205. */
  1206. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1207. var materialValues = material.values || technique.parameters;
  1208. var techniqueUniforms = technique.uniforms;
  1209. /**
  1210. * Prepare values here (not matrices)
  1211. */
  1212. for (var unif in unTreatedUniforms) {
  1213. var uniform = unTreatedUniforms[unif];
  1214. var type = uniform.type;
  1215. var value = materialValues[techniqueUniforms[unif]];
  1216. if (value === undefined) {
  1217. // In case the value is the same for all materials
  1218. value = uniform.value;
  1219. }
  1220. if (!value) {
  1221. continue;
  1222. }
  1223. var onLoadTexture = function (uniformName) {
  1224. return function (texture) {
  1225. if (uniform.value) {
  1226. // Static uniform
  1227. shaderMaterial.setTexture(uniformName, texture);
  1228. delete unTreatedUniforms[uniformName];
  1229. }
  1230. };
  1231. };
  1232. // Texture (sampler2D)
  1233. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1234. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  1235. }
  1236. else {
  1237. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  1238. // Static uniform
  1239. delete unTreatedUniforms[unif];
  1240. }
  1241. }
  1242. }
  1243. };
  1244. /**
  1245. * Shader compilation failed
  1246. */
  1247. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1248. return function (effect, error) {
  1249. BABYLON.Tools.Error("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1250. shaderMaterial.dispose(true);
  1251. onError();
  1252. };
  1253. };
  1254. /**
  1255. * Shader compilation success
  1256. */
  1257. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1258. return function (_) {
  1259. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1260. shaderMaterial.onBind = function (mesh) {
  1261. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1262. };
  1263. };
  1264. };
  1265. /**
  1266. * Returns the appropriate uniform if already handled by babylon
  1267. */
  1268. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1269. for (var unif in technique.uniforms) {
  1270. var uniform = technique.uniforms[unif];
  1271. var uniformParameter = technique.parameters[uniform];
  1272. if (tokenizer.currentIdentifier === unif) {
  1273. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1274. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1275. if (transformIndex !== -1) {
  1276. delete unTreatedUniforms[unif];
  1277. return babylonTransforms[transformIndex];
  1278. }
  1279. }
  1280. }
  1281. }
  1282. return tokenizer.currentIdentifier;
  1283. };
  1284. /**
  1285. * All shaders loaded. Create materials one by one
  1286. */
  1287. var importMaterials = function (gltfRuntime) {
  1288. // Create materials
  1289. for (var mat in gltfRuntime.materials) {
  1290. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1291. }
  1292. };
  1293. /**
  1294. * Implementation of the base glTF spec
  1295. */
  1296. var GLTFLoaderBase = (function () {
  1297. function GLTFLoaderBase() {
  1298. }
  1299. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1300. var gltfRuntime = {
  1301. extensions: {},
  1302. accessors: {},
  1303. buffers: {},
  1304. bufferViews: {},
  1305. meshes: {},
  1306. lights: {},
  1307. cameras: {},
  1308. nodes: {},
  1309. images: {},
  1310. textures: {},
  1311. shaders: {},
  1312. programs: {},
  1313. samplers: {},
  1314. techniques: {},
  1315. materials: {},
  1316. animations: {},
  1317. skins: {},
  1318. extensionsUsed: [],
  1319. scenes: {},
  1320. buffersCount: 0,
  1321. shaderscount: 0,
  1322. scene: scene,
  1323. rootUrl: rootUrl,
  1324. loadedBufferCount: 0,
  1325. loadedBufferViews: {},
  1326. loadedShaderCount: 0,
  1327. importOnlyMeshes: false,
  1328. dummyNodes: []
  1329. };
  1330. // Parse
  1331. if (parsedData.extensions) {
  1332. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1333. }
  1334. if (parsedData.extensionsUsed) {
  1335. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1336. }
  1337. if (parsedData.buffers) {
  1338. parseBuffers(parsedData.buffers, gltfRuntime);
  1339. }
  1340. if (parsedData.bufferViews) {
  1341. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1342. }
  1343. if (parsedData.accessors) {
  1344. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1345. }
  1346. if (parsedData.meshes) {
  1347. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1348. }
  1349. if (parsedData.lights) {
  1350. parseObject(parsedData.lights, "lights", gltfRuntime);
  1351. }
  1352. if (parsedData.cameras) {
  1353. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1354. }
  1355. if (parsedData.nodes) {
  1356. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1357. }
  1358. if (parsedData.images) {
  1359. parseObject(parsedData.images, "images", gltfRuntime);
  1360. }
  1361. if (parsedData.textures) {
  1362. parseObject(parsedData.textures, "textures", gltfRuntime);
  1363. }
  1364. if (parsedData.shaders) {
  1365. parseShaders(parsedData.shaders, gltfRuntime);
  1366. }
  1367. if (parsedData.programs) {
  1368. parseObject(parsedData.programs, "programs", gltfRuntime);
  1369. }
  1370. if (parsedData.samplers) {
  1371. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1372. }
  1373. if (parsedData.techniques) {
  1374. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1375. }
  1376. if (parsedData.materials) {
  1377. parseObject(parsedData.materials, "materials", gltfRuntime);
  1378. }
  1379. if (parsedData.animations) {
  1380. parseObject(parsedData.animations, "animations", gltfRuntime);
  1381. }
  1382. if (parsedData.skins) {
  1383. parseObject(parsedData.skins, "skins", gltfRuntime);
  1384. }
  1385. if (parsedData.scenes) {
  1386. gltfRuntime.scenes = parsedData.scenes;
  1387. }
  1388. if (parsedData.scene && parsedData.scenes) {
  1389. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1390. }
  1391. return gltfRuntime;
  1392. };
  1393. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1394. var buffer = gltfRuntime.buffers[id];
  1395. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  1396. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  1397. }
  1398. else {
  1399. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, null, true, onError);
  1400. }
  1401. };
  1402. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1403. var texture = gltfRuntime.textures[id];
  1404. if (!texture || !texture.source) {
  1405. onError();
  1406. return;
  1407. }
  1408. if (texture.babylonTexture) {
  1409. onSuccess(null);
  1410. return;
  1411. }
  1412. var source = gltfRuntime.images[texture.source];
  1413. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  1414. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  1415. }
  1416. else {
  1417. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, onError);
  1418. }
  1419. };
  1420. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1421. var texture = gltfRuntime.textures[id];
  1422. if (texture.babylonTexture) {
  1423. onSuccess(texture.babylonTexture);
  1424. return;
  1425. }
  1426. var sampler = gltfRuntime.samplers[texture.sampler];
  1427. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1428. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1429. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1430. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1431. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1432. var blob = new Blob([buffer]);
  1433. var blobURL = URL.createObjectURL(blob);
  1434. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1435. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1436. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  1437. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  1438. newTexture.name = id;
  1439. texture.babylonTexture = newTexture;
  1440. onSuccess(newTexture);
  1441. };
  1442. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1443. var shader = gltfRuntime.shaders[id];
  1444. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  1445. var shaderString = atob(shader.uri.split(",")[1]);
  1446. onSuccess(shaderString);
  1447. }
  1448. else {
  1449. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, onError);
  1450. }
  1451. };
  1452. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1453. var material = gltfRuntime.materials[id];
  1454. var technique = gltfRuntime.techniques[material.technique];
  1455. if (!technique) {
  1456. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  1457. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  1458. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1459. onSuccess(defaultMaterial);
  1460. return;
  1461. }
  1462. var program = gltfRuntime.programs[technique.program];
  1463. var states = technique.states;
  1464. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1465. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1466. var newVertexShader = "";
  1467. var newPixelShader = "";
  1468. var vertexTokenizer = new Tokenizer(vertexShader);
  1469. var pixelTokenizer = new Tokenizer(pixelShader);
  1470. var unTreatedUniforms = {};
  1471. var uniforms = [];
  1472. var attributes = [];
  1473. var samplers = [];
  1474. // Fill uniform, sampler2D and attributes
  1475. for (var unif in technique.uniforms) {
  1476. var uniform = technique.uniforms[unif];
  1477. var uniformParameter = technique.parameters[uniform];
  1478. unTreatedUniforms[unif] = uniformParameter;
  1479. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1480. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1481. if (transformIndex !== -1) {
  1482. uniforms.push(babylonTransforms[transformIndex]);
  1483. delete unTreatedUniforms[unif];
  1484. }
  1485. else {
  1486. uniforms.push(unif);
  1487. }
  1488. }
  1489. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  1490. samplers.push(unif);
  1491. }
  1492. else {
  1493. uniforms.push(unif);
  1494. }
  1495. }
  1496. for (var attr in technique.attributes) {
  1497. var attribute = technique.attributes[attr];
  1498. var attributeParameter = technique.parameters[attribute];
  1499. if (attributeParameter.semantic) {
  1500. attributes.push(getAttribute(attributeParameter));
  1501. }
  1502. }
  1503. // Configure vertex shader
  1504. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1505. var tokenType = vertexTokenizer.currentToken;
  1506. if (tokenType !== ETokenType.IDENTIFIER) {
  1507. newVertexShader += vertexTokenizer.currentString;
  1508. continue;
  1509. }
  1510. var foundAttribute = false;
  1511. for (var attr in technique.attributes) {
  1512. var attribute = technique.attributes[attr];
  1513. var attributeParameter = technique.parameters[attribute];
  1514. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1515. newVertexShader += getAttribute(attributeParameter);
  1516. foundAttribute = true;
  1517. break;
  1518. }
  1519. }
  1520. if (foundAttribute) {
  1521. continue;
  1522. }
  1523. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1524. }
  1525. // Configure pixel shader
  1526. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1527. var tokenType = pixelTokenizer.currentToken;
  1528. if (tokenType !== ETokenType.IDENTIFIER) {
  1529. newPixelShader += pixelTokenizer.currentString;
  1530. continue;
  1531. }
  1532. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1533. }
  1534. // Create shader material
  1535. var shaderPath = {
  1536. vertex: program.vertexShader + id,
  1537. fragment: program.fragmentShader + id
  1538. };
  1539. var options = {
  1540. attributes: attributes,
  1541. uniforms: uniforms,
  1542. samplers: samplers,
  1543. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1544. };
  1545. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1546. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1547. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1548. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1549. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1550. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1551. if (states && states.functions) {
  1552. var functions = states.functions;
  1553. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  1554. shaderMaterial.backFaceCulling = false;
  1555. }
  1556. var blendFunc = functions.blendFuncSeparate;
  1557. if (blendFunc) {
  1558. 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) {
  1559. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1560. }
  1561. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1562. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  1563. }
  1564. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1565. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  1566. }
  1567. 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) {
  1568. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  1569. }
  1570. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1571. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  1572. }
  1573. 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) {
  1574. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  1575. }
  1576. }
  1577. }
  1578. };
  1579. return GLTFLoaderBase;
  1580. }());
  1581. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  1582. /**
  1583. * glTF V1 Loader
  1584. */
  1585. var GLTFLoader = (function () {
  1586. function GLTFLoader() {
  1587. }
  1588. GLTFLoader.RegisterExtension = function (extension) {
  1589. if (GLTFLoader.Extensions[extension.name]) {
  1590. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1591. return;
  1592. }
  1593. GLTFLoader.Extensions[extension.name] = extension;
  1594. };
  1595. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onError, onProgress) {
  1596. var _this = this;
  1597. scene.useRightHandedSystem = true;
  1598. var gltfRuntime = GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1599. gltfRuntime.importOnlyMeshes = true;
  1600. if (meshesNames === "") {
  1601. gltfRuntime.importMeshesNames = [];
  1602. }
  1603. else if (typeof meshesNames === "string") {
  1604. gltfRuntime.importMeshesNames = [meshesNames];
  1605. }
  1606. else if (meshesNames && !(meshesNames instanceof Array)) {
  1607. gltfRuntime.importMeshesNames = [meshesNames];
  1608. }
  1609. else {
  1610. gltfRuntime.importMeshesNames = [];
  1611. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1612. }
  1613. // Create nodes
  1614. _this._createNodes(gltfRuntime);
  1615. var meshes = [];
  1616. var skeletons = [];
  1617. // Fill arrays of meshes and skeletons
  1618. for (var nde in gltfRuntime.nodes) {
  1619. var node = gltfRuntime.nodes[nde];
  1620. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1621. meshes.push(node.babylonNode);
  1622. }
  1623. }
  1624. for (var skl in gltfRuntime.skins) {
  1625. var skin = gltfRuntime.skins[skl];
  1626. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1627. skeletons.push(skin.babylonSkeleton);
  1628. }
  1629. }
  1630. // Load buffers, shaders, materials, etc.
  1631. _this._loadBuffersAsync(gltfRuntime, function () {
  1632. _this._loadShadersAsync(gltfRuntime, function () {
  1633. importMaterials(gltfRuntime);
  1634. postLoad(gltfRuntime);
  1635. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1636. onSuccess(meshes, null, skeletons);
  1637. }
  1638. });
  1639. }, onProgress);
  1640. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1641. onSuccess(meshes, null, skeletons);
  1642. }
  1643. }, onError);
  1644. return true;
  1645. };
  1646. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1647. var _this = this;
  1648. scene.useRightHandedSystem = true;
  1649. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1650. // Load runtime extensios
  1651. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  1652. // Create nodes
  1653. _this._createNodes(gltfRuntime);
  1654. // Load buffers, shaders, materials, etc.
  1655. _this._loadBuffersAsync(gltfRuntime, function () {
  1656. _this._loadShadersAsync(gltfRuntime, function () {
  1657. importMaterials(gltfRuntime);
  1658. postLoad(gltfRuntime);
  1659. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  1660. onSuccess();
  1661. }
  1662. });
  1663. });
  1664. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  1665. onSuccess();
  1666. }
  1667. }, onError);
  1668. }, onError);
  1669. };
  1670. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1671. var hasShaders = false;
  1672. var processShader = function (sha, shader) {
  1673. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1674. gltfRuntime.loadedShaderCount++;
  1675. if (shaderString) {
  1676. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1677. }
  1678. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1679. onload();
  1680. }
  1681. }, function () {
  1682. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1683. });
  1684. };
  1685. for (var sha in gltfRuntime.shaders) {
  1686. hasShaders = true;
  1687. var shader = gltfRuntime.shaders[sha];
  1688. if (shader) {
  1689. processShader.bind(this, sha, shader)();
  1690. }
  1691. else {
  1692. BABYLON.Tools.Error("No shader named: " + sha);
  1693. }
  1694. }
  1695. if (!hasShaders) {
  1696. onload();
  1697. }
  1698. };
  1699. ;
  1700. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onload, onProgress) {
  1701. var hasBuffers = false;
  1702. var processBuffer = function (buf, buffer) {
  1703. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  1704. gltfRuntime.loadedBufferCount++;
  1705. if (bufferView) {
  1706. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  1707. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  1708. }
  1709. gltfRuntime.loadedBufferViews[buf] = bufferView;
  1710. }
  1711. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  1712. onload();
  1713. }
  1714. }, function () {
  1715. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  1716. });
  1717. };
  1718. for (var buf in gltfRuntime.buffers) {
  1719. hasBuffers = true;
  1720. var buffer = gltfRuntime.buffers[buf];
  1721. if (buffer) {
  1722. processBuffer.bind(this, buf, buffer)();
  1723. }
  1724. else {
  1725. BABYLON.Tools.Error("No buffer named: " + buf);
  1726. }
  1727. }
  1728. if (!hasBuffers) {
  1729. onload();
  1730. }
  1731. };
  1732. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  1733. var currentScene = gltfRuntime.currentScene;
  1734. if (currentScene) {
  1735. // Only one scene even if multiple scenes are defined
  1736. for (var i = 0; i < currentScene.nodes.length; i++) {
  1737. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1738. }
  1739. }
  1740. else {
  1741. // Load all scenes
  1742. for (var thing in gltfRuntime.scenes) {
  1743. currentScene = gltfRuntime.scenes[thing];
  1744. for (var i = 0; i < currentScene.nodes.length; i++) {
  1745. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1746. }
  1747. }
  1748. }
  1749. };
  1750. return GLTFLoader;
  1751. }());
  1752. GLTFLoader.Extensions = {};
  1753. GLTF1.GLTFLoader = GLTFLoader;
  1754. ;
  1755. BABYLON.GLTFFileLoader.GLTFLoaderV1 = new GLTFLoader();
  1756. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  1757. })(BABYLON || (BABYLON = {}));
  1758. //# sourceMappingURL=babylon.glTFLoader.js.map
  1759. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1760. var BABYLON;
  1761. (function (BABYLON) {
  1762. var GLTF1;
  1763. (function (GLTF1) {
  1764. /**
  1765. * Utils functions for GLTF
  1766. */
  1767. var GLTFUtils = (function () {
  1768. function GLTFUtils() {
  1769. }
  1770. /**
  1771. * Sets the given "parameter" matrix
  1772. * @param scene: the {BABYLON.Scene} object
  1773. * @param source: the source node where to pick the matrix
  1774. * @param parameter: the GLTF technique parameter
  1775. * @param uniformName: the name of the shader's uniform
  1776. * @param shaderMaterial: the shader material
  1777. */
  1778. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  1779. var mat = null;
  1780. if (parameter.semantic === "MODEL") {
  1781. mat = source.getWorldMatrix();
  1782. }
  1783. else if (parameter.semantic === "PROJECTION") {
  1784. mat = scene.getProjectionMatrix();
  1785. }
  1786. else if (parameter.semantic === "VIEW") {
  1787. mat = scene.getViewMatrix();
  1788. }
  1789. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  1790. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  1791. }
  1792. else if (parameter.semantic === "MODELVIEW") {
  1793. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  1794. }
  1795. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  1796. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  1797. }
  1798. else if (parameter.semantic === "MODELINVERSE") {
  1799. mat = source.getWorldMatrix().invert();
  1800. }
  1801. else if (parameter.semantic === "VIEWINVERSE") {
  1802. mat = scene.getViewMatrix().invert();
  1803. }
  1804. else if (parameter.semantic === "PROJECTIONINVERSE") {
  1805. mat = scene.getProjectionMatrix().invert();
  1806. }
  1807. else if (parameter.semantic === "MODELVIEWINVERSE") {
  1808. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  1809. }
  1810. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  1811. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  1812. }
  1813. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  1814. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  1815. }
  1816. else {
  1817. debugger;
  1818. }
  1819. switch (parameter.type) {
  1820. case GLTF1.EParameterType.FLOAT_MAT2:
  1821. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  1822. break;
  1823. case GLTF1.EParameterType.FLOAT_MAT3:
  1824. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  1825. break;
  1826. case GLTF1.EParameterType.FLOAT_MAT4:
  1827. shaderMaterial.setMatrix(uniformName, mat);
  1828. break;
  1829. default: break;
  1830. }
  1831. };
  1832. /**
  1833. * Sets the given "parameter" matrix
  1834. * @param shaderMaterial: the shader material
  1835. * @param uniform: the name of the shader's uniform
  1836. * @param value: the value of the uniform
  1837. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  1838. */
  1839. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  1840. switch (type) {
  1841. case GLTF1.EParameterType.FLOAT:
  1842. shaderMaterial.setFloat(uniform, value);
  1843. return true;
  1844. case GLTF1.EParameterType.FLOAT_VEC2:
  1845. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  1846. return true;
  1847. case GLTF1.EParameterType.FLOAT_VEC3:
  1848. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  1849. return true;
  1850. case GLTF1.EParameterType.FLOAT_VEC4:
  1851. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  1852. return true;
  1853. default: return false;
  1854. }
  1855. };
  1856. /**
  1857. * If the uri is a base64 string
  1858. * @param uri: the uri to test
  1859. */
  1860. GLTFUtils.IsBase64 = function (uri) {
  1861. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1862. };
  1863. /**
  1864. * Decode the base64 uri
  1865. * @param uri: the uri to decode
  1866. */
  1867. GLTFUtils.DecodeBase64 = function (uri) {
  1868. var decodedString = atob(uri.split(",")[1]);
  1869. var bufferLength = decodedString.length;
  1870. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1871. for (var i = 0; i < bufferLength; i++) {
  1872. bufferView[i] = decodedString.charCodeAt(i);
  1873. }
  1874. return bufferView.buffer;
  1875. };
  1876. /**
  1877. * Returns the wrap mode of the texture
  1878. * @param mode: the mode value
  1879. */
  1880. GLTFUtils.GetWrapMode = function (mode) {
  1881. switch (mode) {
  1882. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1883. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1884. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1885. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1886. }
  1887. };
  1888. /**
  1889. * Returns the byte stride giving an accessor
  1890. * @param accessor: the GLTF accessor objet
  1891. */
  1892. GLTFUtils.GetByteStrideFromType = function (accessor) {
  1893. // Needs this function since "byteStride" isn't requiered in glTF format
  1894. var type = accessor.type;
  1895. switch (type) {
  1896. case "VEC2": return 2;
  1897. case "VEC3": return 3;
  1898. case "VEC4": return 4;
  1899. case "MAT2": return 4;
  1900. case "MAT3": return 9;
  1901. case "MAT4": return 16;
  1902. default: return 1;
  1903. }
  1904. };
  1905. /**
  1906. * Returns the texture filter mode giving a mode value
  1907. * @param mode: the filter mode value
  1908. */
  1909. GLTFUtils.GetTextureFilterMode = function (mode) {
  1910. switch (mode) {
  1911. case GLTF1.ETextureFilterType.LINEAR:
  1912. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  1913. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1914. case GLTF1.ETextureFilterType.NEAREST:
  1915. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1916. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1917. }
  1918. };
  1919. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  1920. var byteOffset = bufferView.byteOffset + byteOffset;
  1921. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  1922. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  1923. throw new Error("Buffer access is out of range");
  1924. }
  1925. var buffer = loadedBufferView.buffer;
  1926. byteOffset += loadedBufferView.byteOffset;
  1927. switch (componentType) {
  1928. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  1929. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  1930. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  1931. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  1932. default: return new Float32Array(buffer, byteOffset, byteLength);
  1933. }
  1934. };
  1935. /**
  1936. * Returns a buffer from its accessor
  1937. * @param gltfRuntime: the GLTF runtime
  1938. * @param accessor: the GLTF accessor
  1939. */
  1940. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  1941. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  1942. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  1943. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  1944. };
  1945. /**
  1946. * Decodes a buffer view into a string
  1947. * @param view: the buffer view
  1948. */
  1949. GLTFUtils.DecodeBufferToText = function (view) {
  1950. var result = "";
  1951. var length = view.byteLength;
  1952. for (var i = 0; i < length; ++i) {
  1953. result += String.fromCharCode(view[i]);
  1954. }
  1955. return result;
  1956. };
  1957. /**
  1958. * Returns the default material of gltf. Related to
  1959. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  1960. * @param scene: the Babylon.js scene
  1961. */
  1962. GLTFUtils.GetDefaultMaterial = function (scene) {
  1963. if (!GLTFUtils._DefaultMaterial) {
  1964. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  1965. "precision highp float;",
  1966. "",
  1967. "uniform mat4 worldView;",
  1968. "uniform mat4 projection;",
  1969. "",
  1970. "attribute vec3 position;",
  1971. "",
  1972. "void main(void)",
  1973. "{",
  1974. " gl_Position = projection * worldView * vec4(position, 1.0);",
  1975. "}"
  1976. ].join("\n");
  1977. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  1978. "precision highp float;",
  1979. "",
  1980. "uniform vec4 u_emission;",
  1981. "",
  1982. "void main(void)",
  1983. "{",
  1984. " gl_FragColor = u_emission;",
  1985. "}"
  1986. ].join("\n");
  1987. var shaderPath = {
  1988. vertex: "GLTFDefaultMaterial",
  1989. fragment: "GLTFDefaultMaterial"
  1990. };
  1991. var options = {
  1992. attributes: ["position"],
  1993. uniforms: ["worldView", "projection", "u_emission"],
  1994. samplers: [],
  1995. needAlphaBlending: false
  1996. };
  1997. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  1998. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  1999. }
  2000. return GLTFUtils._DefaultMaterial;
  2001. };
  2002. return GLTFUtils;
  2003. }());
  2004. // The GLTF default material
  2005. GLTFUtils._DefaultMaterial = null;
  2006. GLTF1.GLTFUtils = GLTFUtils;
  2007. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2008. })(BABYLON || (BABYLON = {}));
  2009. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  2010. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2011. var BABYLON;
  2012. (function (BABYLON) {
  2013. var GLTF1;
  2014. (function (GLTF1) {
  2015. var GLTFLoaderExtension = (function () {
  2016. function GLTFLoaderExtension(name) {
  2017. this._name = name;
  2018. }
  2019. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  2020. get: function () {
  2021. return this._name;
  2022. },
  2023. enumerable: true,
  2024. configurable: true
  2025. });
  2026. /**
  2027. * Defines an override for loading the runtime
  2028. * Return true to stop further extensions from loading the runtime
  2029. */
  2030. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2031. return false;
  2032. };
  2033. /**
  2034. * Defines an onverride for creating gltf runtime
  2035. * Return true to stop further extensions from creating the runtime
  2036. */
  2037. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2038. return false;
  2039. };
  2040. /**
  2041. * Defines an override for loading buffers
  2042. * Return true to stop further extensions from loading this buffer
  2043. */
  2044. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2045. return false;
  2046. };
  2047. /**
  2048. * Defines an override for loading texture buffers
  2049. * Return true to stop further extensions from loading this texture data
  2050. */
  2051. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2052. return false;
  2053. };
  2054. /**
  2055. * Defines an override for creating textures
  2056. * Return true to stop further extensions from loading this texture
  2057. */
  2058. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2059. return false;
  2060. };
  2061. /**
  2062. * Defines an override for loading shader strings
  2063. * Return true to stop further extensions from loading this shader data
  2064. */
  2065. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2066. return false;
  2067. };
  2068. /**
  2069. * Defines an override for loading materials
  2070. * Return true to stop further extensions from loading this material
  2071. */
  2072. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2073. return false;
  2074. };
  2075. // ---------
  2076. // Utilities
  2077. // ---------
  2078. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2079. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2080. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  2081. }, function () {
  2082. setTimeout(function () {
  2083. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2084. });
  2085. });
  2086. };
  2087. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2088. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2089. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  2090. }, function () {
  2091. setTimeout(function () {
  2092. onSuccess();
  2093. });
  2094. });
  2095. };
  2096. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2097. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2098. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2099. }, function () {
  2100. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2101. });
  2102. };
  2103. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  2104. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  2105. };
  2106. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2107. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2108. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2109. }, function () {
  2110. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2111. });
  2112. };
  2113. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2114. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2115. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2116. }, function () {
  2117. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2118. });
  2119. };
  2120. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2121. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2122. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2123. }, function () {
  2124. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2125. });
  2126. };
  2127. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2128. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2129. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2130. }, function () {
  2131. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2132. });
  2133. };
  2134. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  2135. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  2136. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  2137. if (func(loaderExtension)) {
  2138. return;
  2139. }
  2140. }
  2141. defaultFunc();
  2142. };
  2143. return GLTFLoaderExtension;
  2144. }());
  2145. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  2146. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2147. })(BABYLON || (BABYLON = {}));
  2148. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2149. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2150. var __extends = (this && this.__extends) || (function () {
  2151. var extendStatics = Object.setPrototypeOf ||
  2152. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2153. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2154. return function (d, b) {
  2155. extendStatics(d, b);
  2156. function __() { this.constructor = d; }
  2157. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2158. };
  2159. })();
  2160. var BABYLON;
  2161. (function (BABYLON) {
  2162. var GLTF1;
  2163. (function (GLTF1) {
  2164. var BinaryExtensionBufferName = "binary_glTF";
  2165. var EContentFormat;
  2166. (function (EContentFormat) {
  2167. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  2168. })(EContentFormat || (EContentFormat = {}));
  2169. ;
  2170. ;
  2171. ;
  2172. var GLTFBinaryExtension = (function (_super) {
  2173. __extends(GLTFBinaryExtension, _super);
  2174. function GLTFBinaryExtension() {
  2175. return _super.call(this, "KHR_binary_glTF") || this;
  2176. }
  2177. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2178. var extensionsUsed = data.json.extensionsUsed;
  2179. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1) {
  2180. return false;
  2181. }
  2182. this._bin = data.bin;
  2183. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2184. return true;
  2185. };
  2186. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2187. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  2188. return false;
  2189. }
  2190. if (id !== BinaryExtensionBufferName) {
  2191. return false;
  2192. }
  2193. onSuccess(this._bin);
  2194. return true;
  2195. };
  2196. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2197. var texture = gltfRuntime.textures[id];
  2198. var source = gltfRuntime.images[texture.source];
  2199. if (!source.extensions || !(this.name in source.extensions)) {
  2200. return false;
  2201. }
  2202. var sourceExt = source.extensions[this.name];
  2203. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  2204. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2205. onSuccess(buffer);
  2206. return true;
  2207. };
  2208. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2209. var shader = gltfRuntime.shaders[id];
  2210. if (!shader.extensions || !(this.name in shader.extensions)) {
  2211. return false;
  2212. }
  2213. var binaryExtensionShader = shader.extensions[this.name];
  2214. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  2215. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2216. setTimeout(function () {
  2217. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  2218. onSuccess(shaderString);
  2219. });
  2220. return true;
  2221. };
  2222. return GLTFBinaryExtension;
  2223. }(GLTF1.GLTFLoaderExtension));
  2224. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  2225. var BinaryReader = (function () {
  2226. function BinaryReader(arrayBuffer) {
  2227. this._arrayBuffer = arrayBuffer;
  2228. this._dataView = new DataView(arrayBuffer);
  2229. this._byteOffset = 0;
  2230. }
  2231. BinaryReader.prototype.getUint32 = function () {
  2232. var value = this._dataView.getUint32(this._byteOffset, true);
  2233. this._byteOffset += 4;
  2234. return value;
  2235. };
  2236. BinaryReader.prototype.getUint8Array = function (length) {
  2237. if (!length) {
  2238. length = this._arrayBuffer.byteLength - this._byteOffset;
  2239. }
  2240. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  2241. this._byteOffset += length;
  2242. return value;
  2243. };
  2244. return BinaryReader;
  2245. }());
  2246. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  2247. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2248. })(BABYLON || (BABYLON = {}));
  2249. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  2250. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2251. var __extends = (this && this.__extends) || (function () {
  2252. var extendStatics = Object.setPrototypeOf ||
  2253. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2254. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2255. return function (d, b) {
  2256. extendStatics(d, b);
  2257. function __() { this.constructor = d; }
  2258. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2259. };
  2260. })();
  2261. var BABYLON;
  2262. (function (BABYLON) {
  2263. var GLTF1;
  2264. (function (GLTF1) {
  2265. ;
  2266. ;
  2267. ;
  2268. var GLTFMaterialsCommonExtension = (function (_super) {
  2269. __extends(GLTFMaterialsCommonExtension, _super);
  2270. function GLTFMaterialsCommonExtension() {
  2271. return _super.call(this, "KHR_materials_common") || this;
  2272. }
  2273. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2274. if (!gltfRuntime.extensions)
  2275. return false;
  2276. var extension = gltfRuntime.extensions[this.name];
  2277. if (!extension)
  2278. return false;
  2279. // Create lights
  2280. var lights = extension.lights;
  2281. if (lights) {
  2282. for (var thing in lights) {
  2283. var light = lights[thing];
  2284. switch (light.type) {
  2285. case "ambient":
  2286. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  2287. var ambient = light.ambient;
  2288. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  2289. break;
  2290. case "point":
  2291. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  2292. var point = light.point;
  2293. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  2294. break;
  2295. case "directional":
  2296. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  2297. var directional = light.directional;
  2298. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  2299. break;
  2300. case "spot":
  2301. var spot = light.spot;
  2302. 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);
  2303. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  2304. break;
  2305. default:
  2306. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  2307. break;
  2308. }
  2309. }
  2310. }
  2311. return false;
  2312. };
  2313. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2314. var material = gltfRuntime.materials[id];
  2315. if (!material || !material.extensions)
  2316. return false;
  2317. var extension = material.extensions[this.name];
  2318. if (!extension)
  2319. return false;
  2320. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2321. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2322. if (extension.technique === "CONSTANT") {
  2323. standardMaterial.disableLighting = true;
  2324. }
  2325. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  2326. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  2327. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  2328. // Ambient
  2329. if (typeof extension.values.ambient === "string") {
  2330. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  2331. }
  2332. else {
  2333. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  2334. }
  2335. // Diffuse
  2336. if (typeof extension.values.diffuse === "string") {
  2337. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  2338. }
  2339. else {
  2340. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  2341. }
  2342. // Emission
  2343. if (typeof extension.values.emission === "string") {
  2344. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  2345. }
  2346. else {
  2347. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  2348. }
  2349. // Specular
  2350. if (typeof extension.values.specular === "string") {
  2351. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  2352. }
  2353. else {
  2354. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  2355. }
  2356. return true;
  2357. };
  2358. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  2359. // Create buffer from texture url
  2360. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2361. // Create texture from buffer
  2362. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  2363. }, onError);
  2364. };
  2365. return GLTFMaterialsCommonExtension;
  2366. }(GLTF1.GLTFLoaderExtension));
  2367. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  2368. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  2369. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2370. })(BABYLON || (BABYLON = {}));
  2371. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  2372. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2373. var BABYLON;
  2374. (function (BABYLON) {
  2375. var GLTF2;
  2376. (function (GLTF2) {
  2377. /**
  2378. * Enums
  2379. */
  2380. var EComponentType;
  2381. (function (EComponentType) {
  2382. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  2383. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  2384. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  2385. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  2386. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  2387. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  2388. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  2389. var EMeshPrimitiveMode;
  2390. (function (EMeshPrimitiveMode) {
  2391. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  2392. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  2393. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  2394. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  2395. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  2396. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  2397. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  2398. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  2399. var ETextureMagFilter;
  2400. (function (ETextureMagFilter) {
  2401. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  2402. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  2403. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  2404. var ETextureMinFilter;
  2405. (function (ETextureMinFilter) {
  2406. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  2407. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  2408. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  2409. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  2410. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  2411. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  2412. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  2413. var ETextureWrapMode;
  2414. (function (ETextureWrapMode) {
  2415. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  2416. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  2417. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  2418. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  2419. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2420. })(BABYLON || (BABYLON = {}));
  2421. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  2422. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2423. var BABYLON;
  2424. (function (BABYLON) {
  2425. var GLTF2;
  2426. (function (GLTF2) {
  2427. var GLTFLoader = (function () {
  2428. function GLTFLoader() {
  2429. }
  2430. GLTFLoader.RegisterExtension = function (extension) {
  2431. if (GLTFLoader.Extensions[extension.name]) {
  2432. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  2433. return;
  2434. }
  2435. GLTFLoader.Extensions[extension.name] = extension;
  2436. // Keep the order of registration so that extensions registered first are called first.
  2437. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  2438. };
  2439. Object.defineProperty(GLTFLoader.prototype, "gltf", {
  2440. get: function () {
  2441. return this._gltf;
  2442. },
  2443. enumerable: true,
  2444. configurable: true
  2445. });
  2446. Object.defineProperty(GLTFLoader.prototype, "babylonScene", {
  2447. get: function () {
  2448. return this._babylonScene;
  2449. },
  2450. enumerable: true,
  2451. configurable: true
  2452. });
  2453. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onError) {
  2454. var _this = this;
  2455. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  2456. var meshes = [];
  2457. if (_this._gltf.nodes) {
  2458. for (var i = 0; i < _this._gltf.nodes.length; i++) {
  2459. var node = _this._gltf.nodes[i];
  2460. if (node.babylonMesh) {
  2461. meshes.push(node.babylonMesh);
  2462. }
  2463. }
  2464. }
  2465. var skeletons = [];
  2466. if (_this._gltf.skins) {
  2467. for (var i = 0; i < _this._gltf.skins.length; i++) {
  2468. var skin = _this._gltf.skins[i];
  2469. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  2470. skeletons.push(skin.babylonSkeleton);
  2471. }
  2472. }
  2473. }
  2474. onSuccess(meshes, null, skeletons);
  2475. }, onError);
  2476. };
  2477. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2478. this._loadAsync(null, scene, data, rootUrl, onSuccess, onError);
  2479. };
  2480. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onError) {
  2481. scene.useRightHandedSystem = true;
  2482. this._clear();
  2483. this._loadData(data);
  2484. this._babylonScene = scene;
  2485. this._rootUrl = rootUrl;
  2486. this._onSuccess = onSuccess;
  2487. this._onError = onError;
  2488. this.addPendingData(this);
  2489. this._loadScene(nodeNames);
  2490. this._loadAnimations();
  2491. this.removePendingData(this);
  2492. };
  2493. GLTFLoader.prototype._onRenderReady = function () {
  2494. this._showMeshes();
  2495. this._startAnimations();
  2496. if (this._errors.length === 0) {
  2497. this._onSuccess();
  2498. }
  2499. else {
  2500. this._errors.forEach(function (error) { return BABYLON.Tools.Error(error); });
  2501. this._errors = [];
  2502. this._onError();
  2503. }
  2504. };
  2505. GLTFLoader.prototype._onLoaderComplete = function () {
  2506. this._errors.forEach(function (error) { return BABYLON.Tools.Error(error); });
  2507. this._errors = [];
  2508. this._clear();
  2509. };
  2510. GLTFLoader.prototype._loadData = function (data) {
  2511. this._gltf = data.json;
  2512. var binaryBuffer;
  2513. var buffers = this._gltf.buffers;
  2514. if (buffers.length > 0 && buffers[0].uri === undefined) {
  2515. binaryBuffer = buffers[0];
  2516. }
  2517. if (data.bin) {
  2518. if (binaryBuffer) {
  2519. if (binaryBuffer.byteLength != data.bin.byteLength) {
  2520. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  2521. }
  2522. }
  2523. else {
  2524. BABYLON.Tools.Warn("Unexpected BIN chunk");
  2525. }
  2526. binaryBuffer.loadedData = data.bin;
  2527. }
  2528. };
  2529. GLTFLoader.prototype._showMeshes = function () {
  2530. var nodes = this._gltf.nodes;
  2531. for (var i = 0; i < nodes.length; i++) {
  2532. var node = nodes[i];
  2533. if (node.babylonMesh) {
  2534. node.babylonMesh.isVisible = true;
  2535. }
  2536. }
  2537. };
  2538. GLTFLoader.prototype._startAnimations = function () {
  2539. var animations = this._gltf.animations;
  2540. if (!animations) {
  2541. return;
  2542. }
  2543. for (var i = 0; i < animations.length; i++) {
  2544. var animation = animations[i];
  2545. for (var j = 0; j < animation.targets.length; j++) {
  2546. this._babylonScene.beginAnimation(animation.targets[j], 0, Number.MAX_VALUE, true);
  2547. }
  2548. }
  2549. };
  2550. GLTFLoader.prototype._clear = function () {
  2551. // Revoke object urls created during load
  2552. if (this._gltf && this._gltf.textures) {
  2553. for (var i = 0; i < this._gltf.textures.length; i++) {
  2554. var texture = this._gltf.textures[i];
  2555. if (texture.blobURL) {
  2556. URL.revokeObjectURL(texture.blobURL);
  2557. }
  2558. }
  2559. }
  2560. this._gltf = undefined;
  2561. this._errors = [];
  2562. this._babylonScene = undefined;
  2563. this._rootUrl = undefined;
  2564. this._defaultMaterial = undefined;
  2565. this._onSuccess = undefined;
  2566. this._onError = undefined;
  2567. this._renderReady = false;
  2568. this._renderPendingCount = 0;
  2569. this._loaderPendingCount = 0;
  2570. };
  2571. GLTFLoader.prototype._loadScene = function (nodeNames) {
  2572. var _this = this;
  2573. var scene = this._gltf.scenes[this._gltf.scene || 0];
  2574. var nodeIndices = scene.nodes;
  2575. this._traverseNodes(nodeIndices, function (node, index, parentNode) {
  2576. node.index = index;
  2577. node.parent = parentNode;
  2578. return true;
  2579. });
  2580. if (nodeNames) {
  2581. if (!(nodeNames instanceof Array)) {
  2582. nodeNames = [nodeNames];
  2583. }
  2584. var filteredNodeIndices = new Array();
  2585. this._traverseNodes(nodeIndices, function (node) {
  2586. if (nodeNames.indexOf(node.name) === -1) {
  2587. return true;
  2588. }
  2589. filteredNodeIndices.push(node.index);
  2590. return false;
  2591. });
  2592. nodeIndices = filteredNodeIndices;
  2593. }
  2594. this._traverseNodes(nodeIndices, function (node) { return _this._loadSkin(node); });
  2595. this._traverseNodes(nodeIndices, function (node) { return _this._loadMesh(node); });
  2596. };
  2597. GLTFLoader.prototype._loadSkin = function (node) {
  2598. var _this = this;
  2599. if (node.skin !== undefined) {
  2600. var skin = this._gltf.skins[node.skin];
  2601. var skeletonId = "skeleton" + node.skin;
  2602. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  2603. skin.index = node.skin;
  2604. for (var i = 0; i < skin.joints.length; i++) {
  2605. this._createBone(this._gltf.nodes[skin.joints[i]], skin);
  2606. }
  2607. if (skin.skeleton === undefined) {
  2608. // TODO: handle when skeleton is not defined
  2609. throw new Error("Not implemented");
  2610. }
  2611. if (skin.inverseBindMatrices === undefined) {
  2612. // TODO: handle when inverse bind matrices are not defined
  2613. throw new Error("Not implemented");
  2614. }
  2615. var accessor = this._gltf.accessors[skin.inverseBindMatrices];
  2616. this._loadAccessorAsync(accessor, function (data) {
  2617. _this._traverseNode(skin.skeleton, function (node, index, parent) { return _this._updateBone(node, parent, skin, data); });
  2618. });
  2619. }
  2620. return true;
  2621. };
  2622. GLTFLoader.prototype._updateBone = function (node, parentNode, skin, inverseBindMatrixData) {
  2623. var jointIndex = skin.joints.indexOf(node.index);
  2624. if (jointIndex === -1) {
  2625. this._createBone(node, skin);
  2626. }
  2627. var babylonBone = node.babylonSkinToBones[skin.index];
  2628. // TODO: explain the math
  2629. var matrix = jointIndex === -1 ? BABYLON.Matrix.Identity() : BABYLON.Matrix.FromArray(inverseBindMatrixData, jointIndex * 16);
  2630. matrix.invertToRef(matrix);
  2631. if (parentNode) {
  2632. babylonBone.setParent(parentNode.babylonSkinToBones[skin.index], false);
  2633. matrix.multiplyToRef(babylonBone.getParent().getInvertedAbsoluteTransform(), matrix);
  2634. }
  2635. babylonBone.updateMatrix(matrix);
  2636. return true;
  2637. };
  2638. GLTFLoader.prototype._createBone = function (node, skin) {
  2639. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton);
  2640. node.babylonSkinToBones = node.babylonSkinToBones || {};
  2641. node.babylonSkinToBones[skin.index] = babylonBone;
  2642. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  2643. node.babylonAnimationTargets.push(babylonBone);
  2644. return babylonBone;
  2645. };
  2646. GLTFLoader.prototype._loadMesh = function (node) {
  2647. var babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  2648. babylonMesh.isVisible = false;
  2649. this._loadTransform(node, babylonMesh);
  2650. if (node.mesh !== undefined) {
  2651. var mesh = this._gltf.meshes[node.mesh];
  2652. this._loadMeshData(node, mesh, babylonMesh);
  2653. }
  2654. babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  2655. node.babylonMesh = babylonMesh;
  2656. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  2657. node.babylonAnimationTargets.push(node.babylonMesh);
  2658. if (node.skin !== undefined) {
  2659. var skin = this._gltf.skins[node.skin];
  2660. babylonMesh.skeleton = skin.babylonSkeleton;
  2661. }
  2662. if (node.camera !== undefined) {
  2663. // TODO: handle cameras
  2664. }
  2665. return true;
  2666. };
  2667. GLTFLoader.prototype._loadMeshData = function (node, mesh, babylonMesh) {
  2668. var _this = this;
  2669. babylonMesh.name = mesh.name || babylonMesh.name;
  2670. var babylonMultiMaterial = new BABYLON.MultiMaterial(babylonMesh.name, this._babylonScene);
  2671. babylonMesh.material = babylonMultiMaterial;
  2672. var geometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene, null, false, babylonMesh);
  2673. var vertexData = new BABYLON.VertexData();
  2674. vertexData.positions = [];
  2675. vertexData.indices = [];
  2676. var subMeshInfos = [];
  2677. var loadedPrimitives = 0;
  2678. var totalPrimitives = mesh.primitives.length;
  2679. var _loop_1 = function (i) {
  2680. var primitive = mesh.primitives[i];
  2681. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  2682. // TODO: handle other primitive modes
  2683. throw new Error("Not implemented");
  2684. }
  2685. this_1._createMorphTargets(node, mesh, primitive, babylonMesh);
  2686. this_1._loadVertexDataAsync(primitive, function (subVertexData) {
  2687. _this._loadMorphTargetsData(mesh, primitive, subVertexData, babylonMesh);
  2688. subMeshInfos.push({
  2689. materialIndex: i,
  2690. verticesStart: vertexData.positions.length,
  2691. verticesCount: subVertexData.positions.length,
  2692. indicesStart: vertexData.indices.length,
  2693. indicesCount: subVertexData.indices.length
  2694. });
  2695. vertexData.merge(subVertexData);
  2696. if (primitive.material === undefined) {
  2697. babylonMultiMaterial.subMaterials[i] = _this._getDefaultMaterial();
  2698. }
  2699. else {
  2700. _this.loadMaterial(primitive.material, function (babylonSubMaterial) {
  2701. if (_this._renderReady) {
  2702. babylonSubMaterial.forceCompilation(babylonMesh, function (babylonSubMaterial) {
  2703. babylonMultiMaterial.subMaterials[i] = babylonSubMaterial;
  2704. });
  2705. }
  2706. else {
  2707. babylonMultiMaterial.subMaterials[i] = babylonSubMaterial;
  2708. }
  2709. });
  2710. }
  2711. if (++loadedPrimitives === totalPrimitives) {
  2712. geometry.setAllVerticesData(vertexData, false);
  2713. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  2714. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  2715. babylonMesh.subMeshes = [];
  2716. subMeshInfos.forEach(function (info) { return new BABYLON.SubMesh(info.materialIndex, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, babylonMesh); });
  2717. }
  2718. });
  2719. };
  2720. var this_1 = this;
  2721. for (var i = 0; i < totalPrimitives; i++) {
  2722. _loop_1(i);
  2723. }
  2724. };
  2725. GLTFLoader.prototype._loadVertexDataAsync = function (primitive, onSuccess) {
  2726. var _this = this;
  2727. var attributes = primitive.attributes;
  2728. if (!attributes) {
  2729. this._errors.push("Primitive has no attributes");
  2730. return;
  2731. }
  2732. var vertexData = new BABYLON.VertexData();
  2733. var loadedAttributes = 0;
  2734. var totalAttributes = Object.keys(attributes).length;
  2735. var _loop_2 = function (semantic) {
  2736. accessor = this_2._gltf.accessors[attributes[semantic]];
  2737. this_2._loadAccessorAsync(accessor, function (data) {
  2738. switch (semantic) {
  2739. case "NORMAL":
  2740. vertexData.normals = data;
  2741. break;
  2742. case "POSITION":
  2743. vertexData.positions = data;
  2744. break;
  2745. case "TANGENT":
  2746. vertexData.tangents = data;
  2747. break;
  2748. case "TEXCOORD_0":
  2749. vertexData.uvs = data;
  2750. break;
  2751. case "TEXCOORD_1":
  2752. vertexData.uvs2 = data;
  2753. break;
  2754. case "JOINTS_0":
  2755. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  2756. break;
  2757. case "WEIGHTS_0":
  2758. vertexData.matricesWeights = data;
  2759. break;
  2760. case "COLOR_0":
  2761. vertexData.colors = data;
  2762. break;
  2763. default:
  2764. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  2765. break;
  2766. }
  2767. if (++loadedAttributes === totalAttributes) {
  2768. var indicesAccessor = _this._gltf.accessors[primitive.indices];
  2769. if (indicesAccessor) {
  2770. _this._loadAccessorAsync(indicesAccessor, function (data) {
  2771. vertexData.indices = data;
  2772. onSuccess(vertexData);
  2773. });
  2774. }
  2775. else {
  2776. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  2777. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  2778. onSuccess(vertexData);
  2779. }
  2780. }
  2781. });
  2782. };
  2783. var this_2 = this, accessor;
  2784. for (var semantic in attributes) {
  2785. _loop_2(semantic);
  2786. }
  2787. };
  2788. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive, babylonMesh) {
  2789. var targets = primitive.targets;
  2790. if (!targets) {
  2791. return;
  2792. }
  2793. if (!babylonMesh.morphTargetManager) {
  2794. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  2795. }
  2796. for (var index = 0; index < targets.length; index++) {
  2797. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  2798. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  2799. }
  2800. };
  2801. GLTFLoader.prototype._loadMorphTargetsData = function (mesh, primitive, vertexData, babylonMesh) {
  2802. var targets = primitive.targets;
  2803. if (!targets) {
  2804. return;
  2805. }
  2806. var _loop_3 = function () {
  2807. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  2808. attributes = targets[index];
  2809. var _loop_4 = function (semantic) {
  2810. accessor = this_3._gltf.accessors[attributes[semantic]];
  2811. this_3._loadAccessorAsync(accessor, function (data) {
  2812. if (accessor.name) {
  2813. babylonMorphTarget.name = accessor.name;
  2814. }
  2815. // glTF stores morph target information as deltas while babylon.js expects the final data.
  2816. // As a result we have to add the original data to the delta to calculate the final data.
  2817. var values = data;
  2818. switch (semantic) {
  2819. case "NORMAL":
  2820. values.forEach(function (v, i) { return values[i] += vertexData.normals[i]; });
  2821. babylonMorphTarget.setNormals(values);
  2822. break;
  2823. case "POSITION":
  2824. values.forEach(function (v, i) { return values[i] += vertexData.positions[i]; });
  2825. babylonMorphTarget.setPositions(values);
  2826. break;
  2827. case "TANGENT":
  2828. // Tangent data for morph targets is stored as xyz delta.
  2829. // The vertexData.tangent is stored as xyzw.
  2830. // So we need to skip every fourth vertexData.tangent.
  2831. for (var i = 0, j = 0; i < values.length; i++, j++) {
  2832. values[i] += vertexData.tangents[j];
  2833. if ((i + 1) % 3 == 0) {
  2834. j++;
  2835. }
  2836. }
  2837. babylonMorphTarget.setTangents(values);
  2838. break;
  2839. default:
  2840. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  2841. break;
  2842. }
  2843. });
  2844. };
  2845. for (var semantic in attributes) {
  2846. _loop_4(semantic);
  2847. }
  2848. };
  2849. var this_3 = this, attributes, accessor;
  2850. for (var index = 0; index < targets.length; index++) {
  2851. _loop_3();
  2852. }
  2853. };
  2854. GLTFLoader.prototype._loadTransform = function (node, babylonMesh) {
  2855. var position = BABYLON.Vector3.Zero();
  2856. var rotation = BABYLON.Quaternion.Identity();
  2857. var scaling = BABYLON.Vector3.One();
  2858. if (node.matrix) {
  2859. var mat = BABYLON.Matrix.FromArray(node.matrix);
  2860. mat.decompose(scaling, rotation, position);
  2861. }
  2862. else {
  2863. if (node.translation)
  2864. position = BABYLON.Vector3.FromArray(node.translation);
  2865. if (node.rotation)
  2866. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  2867. if (node.scale)
  2868. scaling = BABYLON.Vector3.FromArray(node.scale);
  2869. }
  2870. babylonMesh.position = position;
  2871. babylonMesh.rotationQuaternion = rotation;
  2872. babylonMesh.scaling = scaling;
  2873. };
  2874. GLTFLoader.prototype._traverseNodes = function (indices, action, parentNode) {
  2875. if (parentNode === void 0) { parentNode = null; }
  2876. for (var i = 0; i < indices.length; i++) {
  2877. this._traverseNode(indices[i], action, parentNode);
  2878. }
  2879. };
  2880. GLTFLoader.prototype._traverseNode = function (index, action, parentNode) {
  2881. if (parentNode === void 0) { parentNode = null; }
  2882. var node = this._gltf.nodes[index];
  2883. if (!action(node, index, parentNode)) {
  2884. return;
  2885. }
  2886. if (node.children) {
  2887. for (var i = 0; i < node.children.length; i++) {
  2888. this._traverseNode(node.children[i], action, node);
  2889. }
  2890. }
  2891. };
  2892. GLTFLoader.prototype._loadAnimations = function () {
  2893. var animations = this._gltf.animations;
  2894. if (!animations || animations.length === 0) {
  2895. return;
  2896. }
  2897. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  2898. var animation = animations[animationIndex];
  2899. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  2900. this._loadAnimationChannel(animation, animationIndex, channelIndex);
  2901. }
  2902. }
  2903. };
  2904. GLTFLoader.prototype._loadAnimationChannel = function (animation, animationIndex, channelIndex) {
  2905. var channel = animation.channels[channelIndex];
  2906. var samplerIndex = channel.sampler;
  2907. var sampler = animation.samplers[samplerIndex];
  2908. var targetNode = this._gltf.nodes[channel.target.node];
  2909. if (!targetNode) {
  2910. BABYLON.Tools.Warn("Animation channel target node (" + channel.target.node + ") does not exist");
  2911. return;
  2912. }
  2913. var targetPath = {
  2914. "translation": "position",
  2915. "rotation": "rotationQuaternion",
  2916. "scale": "scaling",
  2917. "weights": "influence"
  2918. }[channel.target.path];
  2919. if (!targetPath) {
  2920. BABYLON.Tools.Warn("Animation channel target path '" + channel.target.path + "' is not valid");
  2921. return;
  2922. }
  2923. var animationType = {
  2924. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  2925. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  2926. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  2927. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  2928. }[targetPath];
  2929. var inputData;
  2930. var outputData;
  2931. var checkSuccess = function () {
  2932. if (!inputData || !outputData) {
  2933. return;
  2934. }
  2935. var outputBufferOffset = 0;
  2936. var getNextOutputValue = {
  2937. "position": function () {
  2938. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  2939. outputBufferOffset += 3;
  2940. return value;
  2941. },
  2942. "rotationQuaternion": function () {
  2943. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  2944. outputBufferOffset += 4;
  2945. return value;
  2946. },
  2947. "scaling": function () {
  2948. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  2949. outputBufferOffset += 3;
  2950. return value;
  2951. },
  2952. "influence": function () {
  2953. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  2954. var value = new Array(numTargets);
  2955. for (var i = 0; i < numTargets; i++) {
  2956. value[i] = outputData[outputBufferOffset++];
  2957. }
  2958. return value;
  2959. },
  2960. }[targetPath];
  2961. var getNextKey = {
  2962. "LINEAR": function (frameIndex) { return ({
  2963. frame: inputData[frameIndex],
  2964. value: getNextOutputValue()
  2965. }); },
  2966. "CUBICSPLINE": function (frameIndex) { return ({
  2967. frame: inputData[frameIndex],
  2968. inTangent: getNextOutputValue(),
  2969. value: getNextOutputValue(),
  2970. outTangent: getNextOutputValue()
  2971. }); },
  2972. }[sampler.interpolation];
  2973. var keys = new Array(inputData.length);
  2974. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  2975. keys[frameIndex] = getNextKey(frameIndex);
  2976. }
  2977. animation.targets = animation.targets || [];
  2978. if (targetPath === "influence") {
  2979. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  2980. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  2981. var morphTarget = morphTargetManager.getTarget(targetIndex);
  2982. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  2983. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  2984. babylonAnimation.setKeys(keys.map(function (key) { return ({
  2985. frame: key.frame,
  2986. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  2987. value: key.value[targetIndex],
  2988. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  2989. }); }));
  2990. morphTarget.animations.push(babylonAnimation);
  2991. animation.targets.push(morphTarget);
  2992. }
  2993. }
  2994. else {
  2995. var animationName = animation.name || "anim" + animationIndex;
  2996. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  2997. babylonAnimation.setKeys(keys);
  2998. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  2999. var target = targetNode.babylonAnimationTargets[i];
  3000. target.animations.push(babylonAnimation.clone());
  3001. animation.targets.push(target);
  3002. }
  3003. }
  3004. };
  3005. this._loadAccessorAsync(this._gltf.accessors[sampler.input], function (data) {
  3006. inputData = data;
  3007. checkSuccess();
  3008. });
  3009. this._loadAccessorAsync(this._gltf.accessors[sampler.output], function (data) {
  3010. outputData = data;
  3011. checkSuccess();
  3012. });
  3013. };
  3014. GLTFLoader.prototype._loadBufferAsync = function (index, onSuccess) {
  3015. var _this = this;
  3016. var buffer = this._gltf.buffers[index];
  3017. this.addPendingData(buffer);
  3018. if (buffer.loadedData) {
  3019. setTimeout(function () {
  3020. onSuccess(buffer.loadedData);
  3021. _this.removePendingData(buffer);
  3022. });
  3023. }
  3024. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  3025. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  3026. buffer.loadedData = new Uint8Array(data);
  3027. setTimeout(function () {
  3028. onSuccess(buffer.loadedData);
  3029. _this.removePendingData(buffer);
  3030. });
  3031. }
  3032. else if (buffer.loadedObservable) {
  3033. buffer.loadedObservable.add(function (buffer) {
  3034. onSuccess(buffer.loadedData);
  3035. _this.removePendingData(buffer);
  3036. });
  3037. }
  3038. else {
  3039. buffer.loadedObservable = new BABYLON.Observable();
  3040. buffer.loadedObservable.add(function (buffer) {
  3041. onSuccess(buffer.loadedData);
  3042. _this.removePendingData(buffer);
  3043. });
  3044. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  3045. buffer.loadedData = new Uint8Array(data);
  3046. buffer.loadedObservable.notifyObservers(buffer);
  3047. buffer.loadedObservable = null;
  3048. }, null, null, true, function (request) {
  3049. _this._errors.push("Failed to load file '" + buffer.uri + "': " + request.statusText + "(" + request.status + ")");
  3050. _this.removePendingData(buffer);
  3051. });
  3052. }
  3053. };
  3054. GLTFLoader.prototype._loadBufferViewAsync = function (bufferView, byteOffset, byteLength, componentType, onSuccess) {
  3055. var _this = this;
  3056. byteOffset += (bufferView.byteOffset || 0);
  3057. this._loadBufferAsync(bufferView.buffer, function (bufferData) {
  3058. if (byteOffset + byteLength > bufferData.byteLength) {
  3059. _this._errors.push("Buffer access is out of range");
  3060. return;
  3061. }
  3062. var buffer = bufferData.buffer;
  3063. byteOffset += bufferData.byteOffset;
  3064. var bufferViewData;
  3065. switch (componentType) {
  3066. case GLTF2.EComponentType.BYTE:
  3067. bufferViewData = new Int8Array(buffer, byteOffset, byteLength);
  3068. break;
  3069. case GLTF2.EComponentType.UNSIGNED_BYTE:
  3070. bufferViewData = new Uint8Array(buffer, byteOffset, byteLength);
  3071. break;
  3072. case GLTF2.EComponentType.SHORT:
  3073. bufferViewData = new Int16Array(buffer, byteOffset, byteLength);
  3074. break;
  3075. case GLTF2.EComponentType.UNSIGNED_SHORT:
  3076. bufferViewData = new Uint16Array(buffer, byteOffset, byteLength);
  3077. break;
  3078. case GLTF2.EComponentType.UNSIGNED_INT:
  3079. bufferViewData = new Uint32Array(buffer, byteOffset, byteLength);
  3080. break;
  3081. case GLTF2.EComponentType.FLOAT:
  3082. bufferViewData = new Float32Array(buffer, byteOffset, byteLength);
  3083. break;
  3084. default:
  3085. _this._errors.push("Invalid component type (" + componentType + ")");
  3086. return;
  3087. }
  3088. onSuccess(bufferViewData);
  3089. });
  3090. };
  3091. GLTFLoader.prototype._loadAccessorAsync = function (accessor, onSuccess) {
  3092. var bufferView = this._gltf.bufferViews[accessor.bufferView];
  3093. var byteOffset = accessor.byteOffset || 0;
  3094. var byteLength = accessor.count * GLTF2.GLTFUtils.GetByteStrideFromType(accessor);
  3095. this._loadBufferViewAsync(bufferView, byteOffset, byteLength, accessor.componentType, onSuccess);
  3096. };
  3097. GLTFLoader.prototype.addPendingData = function (data) {
  3098. if (!this._renderReady) {
  3099. this._renderPendingCount++;
  3100. }
  3101. this.addLoaderPendingData(data);
  3102. };
  3103. GLTFLoader.prototype.removePendingData = function (data) {
  3104. if (!this._renderReady) {
  3105. if (--this._renderPendingCount === 0) {
  3106. this._renderReady = true;
  3107. this._onRenderReady();
  3108. }
  3109. }
  3110. this.removeLoaderPendingData(data);
  3111. };
  3112. GLTFLoader.prototype.addLoaderPendingData = function (data) {
  3113. this._loaderPendingCount++;
  3114. };
  3115. GLTFLoader.prototype.removeLoaderPendingData = function (data) {
  3116. if (--this._loaderPendingCount === 0) {
  3117. this._onLoaderComplete();
  3118. }
  3119. };
  3120. GLTFLoader.prototype._getDefaultMaterial = function () {
  3121. if (!this._defaultMaterial) {
  3122. var id = "__gltf_default";
  3123. var material = this._babylonScene.getMaterialByName(id);
  3124. if (!material) {
  3125. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  3126. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  3127. material.metallic = 1;
  3128. material.roughness = 1;
  3129. }
  3130. this._defaultMaterial = material;
  3131. }
  3132. return this._defaultMaterial;
  3133. };
  3134. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (material) {
  3135. // Ensure metallic workflow
  3136. material.babylonMaterial.metallic = 1;
  3137. material.babylonMaterial.roughness = 1;
  3138. var properties = material.pbrMetallicRoughness;
  3139. if (!properties) {
  3140. return;
  3141. }
  3142. material.babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  3143. material.babylonMaterial.metallic = properties.metallicFactor === undefined ? 1 : properties.metallicFactor;
  3144. material.babylonMaterial.roughness = properties.roughnessFactor === undefined ? 1 : properties.roughnessFactor;
  3145. if (properties.baseColorTexture) {
  3146. material.babylonMaterial.albedoTexture = this.loadTexture(properties.baseColorTexture);
  3147. this.loadMaterialAlphaProperties(material);
  3148. }
  3149. if (properties.metallicRoughnessTexture) {
  3150. material.babylonMaterial.metallicTexture = this.loadTexture(properties.metallicRoughnessTexture);
  3151. material.babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  3152. material.babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  3153. material.babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  3154. }
  3155. };
  3156. GLTFLoader.prototype.loadMaterial = function (index, assign) {
  3157. var material = this._gltf.materials[index];
  3158. material.index = index;
  3159. if (material.babylonMaterial) {
  3160. assign(material.babylonMaterial);
  3161. return;
  3162. }
  3163. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, material, assign)) {
  3164. return;
  3165. }
  3166. this.createPbrMaterial(material);
  3167. this.loadMaterialBaseProperties(material);
  3168. this._loadMaterialMetallicRoughnessProperties(material);
  3169. assign(material.babylonMaterial);
  3170. };
  3171. GLTFLoader.prototype.createPbrMaterial = function (material) {
  3172. material.babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  3173. material.babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  3174. material.babylonMaterial.useScalarInLinearSpace = true;
  3175. };
  3176. GLTFLoader.prototype.loadMaterialBaseProperties = function (material) {
  3177. material.babylonMaterial.useEmissiveAsIllumination = (material.emissiveFactor || material.emissiveTexture) ? true : false;
  3178. material.babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  3179. if (material.doubleSided) {
  3180. material.babylonMaterial.backFaceCulling = false;
  3181. material.babylonMaterial.twoSidedLighting = true;
  3182. }
  3183. if (material.normalTexture) {
  3184. material.babylonMaterial.bumpTexture = this.loadTexture(material.normalTexture);
  3185. if (material.normalTexture.scale !== undefined) {
  3186. material.babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  3187. }
  3188. }
  3189. if (material.occlusionTexture) {
  3190. material.babylonMaterial.ambientTexture = this.loadTexture(material.occlusionTexture);
  3191. material.babylonMaterial.useAmbientInGrayScale = true;
  3192. if (material.occlusionTexture.strength !== undefined) {
  3193. material.babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  3194. }
  3195. }
  3196. if (material.emissiveTexture) {
  3197. material.babylonMaterial.emissiveTexture = this.loadTexture(material.emissiveTexture);
  3198. }
  3199. };
  3200. GLTFLoader.prototype.loadMaterialAlphaProperties = function (material) {
  3201. var alphaMode = material.alphaMode || "OPAQUE";
  3202. switch (alphaMode) {
  3203. case "OPAQUE":
  3204. // default is opaque
  3205. break;
  3206. case "MASK":
  3207. material.babylonMaterial.albedoTexture.hasAlpha = true;
  3208. material.babylonMaterial.useAlphaFromAlbedoTexture = false;
  3209. break;
  3210. case "BLEND":
  3211. material.babylonMaterial.albedoTexture.hasAlpha = true;
  3212. material.babylonMaterial.useAlphaFromAlbedoTexture = true;
  3213. break;
  3214. default:
  3215. BABYLON.Tools.Warn("Invalid alpha mode '" + material.alphaMode + "'");
  3216. break;
  3217. }
  3218. };
  3219. GLTFLoader.prototype.loadTexture = function (textureInfo) {
  3220. var _this = this;
  3221. var texture = this._gltf.textures[textureInfo.index];
  3222. var texCoord = textureInfo.texCoord || 0;
  3223. if (!texture || texture.source === undefined) {
  3224. return null;
  3225. }
  3226. // check the cache first
  3227. var babylonTexture;
  3228. if (texture.babylonTextures) {
  3229. babylonTexture = texture.babylonTextures[texCoord];
  3230. if (!babylonTexture) {
  3231. for (var i = 0; i < texture.babylonTextures.length; i++) {
  3232. babylonTexture = texture.babylonTextures[i];
  3233. if (babylonTexture) {
  3234. babylonTexture = babylonTexture.clone();
  3235. babylonTexture.coordinatesIndex = texCoord;
  3236. break;
  3237. }
  3238. }
  3239. }
  3240. return babylonTexture;
  3241. }
  3242. var source = this._gltf.images[texture.source];
  3243. var url;
  3244. if (!source.uri) {
  3245. var bufferView = this._gltf.bufferViews[source.bufferView];
  3246. this._loadBufferViewAsync(bufferView, 0, bufferView.byteLength, GLTF2.EComponentType.UNSIGNED_BYTE, function (data) {
  3247. texture.blobURL = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  3248. texture.babylonTextures[texCoord].updateURL(texture.blobURL);
  3249. });
  3250. }
  3251. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  3252. var data = new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri));
  3253. texture.blobURL = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  3254. url = texture.blobURL;
  3255. }
  3256. else {
  3257. url = this._rootUrl + source.uri;
  3258. }
  3259. var sampler = (texture.sampler === undefined ? {} : this._gltf.samplers[texture.sampler]);
  3260. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  3261. var samplingMode = GLTF2.GLTFUtils.GetTextureFilterMode(sampler.minFilter);
  3262. this.addPendingData(texture);
  3263. var babylonTexture = new BABYLON.Texture(url, this._babylonScene, noMipMaps, false, samplingMode, function () {
  3264. _this.removePendingData(texture);
  3265. }, function () {
  3266. _this._errors.push("Failed to load texture '" + source.uri + "'");
  3267. _this.removePendingData(texture);
  3268. });
  3269. babylonTexture.coordinatesIndex = texCoord;
  3270. babylonTexture.wrapU = GLTF2.GLTFUtils.GetWrapMode(sampler.wrapS);
  3271. babylonTexture.wrapV = GLTF2.GLTFUtils.GetWrapMode(sampler.wrapT);
  3272. babylonTexture.name = texture.name;
  3273. // Cache the texture
  3274. texture.babylonTextures = texture.babylonTextures || [];
  3275. texture.babylonTextures[texCoord] = babylonTexture;
  3276. return babylonTexture;
  3277. };
  3278. return GLTFLoader;
  3279. }());
  3280. GLTFLoader.Extensions = {};
  3281. GLTF2.GLTFLoader = GLTFLoader;
  3282. BABYLON.GLTFFileLoader.GLTFLoaderV2 = new GLTFLoader();
  3283. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3284. })(BABYLON || (BABYLON = {}));
  3285. //# sourceMappingURL=babylon.glTFLoader.js.map
  3286. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  3287. var BABYLON;
  3288. (function (BABYLON) {
  3289. var GLTF2;
  3290. (function (GLTF2) {
  3291. /**
  3292. * Utils functions for GLTF
  3293. */
  3294. var GLTFUtils = (function () {
  3295. function GLTFUtils() {
  3296. }
  3297. /**
  3298. * If the uri is a base64 string
  3299. * @param uri: the uri to test
  3300. */
  3301. GLTFUtils.IsBase64 = function (uri) {
  3302. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  3303. };
  3304. /**
  3305. * Decode the base64 uri
  3306. * @param uri: the uri to decode
  3307. */
  3308. GLTFUtils.DecodeBase64 = function (uri) {
  3309. var decodedString = atob(uri.split(",")[1]);
  3310. var bufferLength = decodedString.length;
  3311. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  3312. for (var i = 0; i < bufferLength; i++) {
  3313. bufferView[i] = decodedString.charCodeAt(i);
  3314. }
  3315. return bufferView.buffer;
  3316. };
  3317. /**
  3318. * Returns the wrap mode of the texture
  3319. * @param mode: the mode value
  3320. */
  3321. GLTFUtils.GetWrapMode = function (mode) {
  3322. switch (mode) {
  3323. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  3324. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  3325. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  3326. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  3327. }
  3328. };
  3329. /**
  3330. * Returns the byte stride giving an accessor
  3331. * @param accessor: the GLTF accessor objet
  3332. */
  3333. GLTFUtils.GetByteStrideFromType = function (accessor) {
  3334. // Needs this function since "byteStride" isn't requiered in glTF format
  3335. var type = accessor.type;
  3336. switch (type) {
  3337. case "VEC2": return 2;
  3338. case "VEC3": return 3;
  3339. case "VEC4": return 4;
  3340. case "MAT2": return 4;
  3341. case "MAT3": return 9;
  3342. case "MAT4": return 16;
  3343. default: return 1;
  3344. }
  3345. };
  3346. /**
  3347. * Returns the texture filter mode giving a mode value
  3348. * @param mode: the filter mode value
  3349. */
  3350. GLTFUtils.GetTextureFilterMode = function (mode) {
  3351. switch (mode) {
  3352. case GLTF2.ETextureMinFilter.LINEAR:
  3353. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST:
  3354. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3355. case GLTF2.ETextureMinFilter.NEAREST:
  3356. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  3357. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  3358. }
  3359. };
  3360. /**
  3361. * Decodes a buffer view into a string
  3362. * @param view: the buffer view
  3363. */
  3364. GLTFUtils.DecodeBufferToText = function (view) {
  3365. var result = "";
  3366. var length = view.byteLength;
  3367. for (var i = 0; i < length; ++i) {
  3368. result += String.fromCharCode(view[i]);
  3369. }
  3370. return result;
  3371. };
  3372. return GLTFUtils;
  3373. }());
  3374. GLTF2.GLTFUtils = GLTFUtils;
  3375. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3376. })(BABYLON || (BABYLON = {}));
  3377. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  3378. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  3379. var BABYLON;
  3380. (function (BABYLON) {
  3381. var GLTF2;
  3382. (function (GLTF2) {
  3383. var GLTFLoaderExtension = (function () {
  3384. function GLTFLoaderExtension() {
  3385. this.enabled = true;
  3386. }
  3387. GLTFLoaderExtension.prototype.loadMaterial = function (loader, material, assign) { return false; };
  3388. GLTFLoaderExtension.LoadMaterial = function (loader, material, assign) {
  3389. return this._ApplyExtensions(function (extension) { return extension.loadMaterial(loader, material, assign); });
  3390. };
  3391. GLTFLoaderExtension._ApplyExtensions = function (action) {
  3392. var extensions = GLTFLoaderExtension._Extensions;
  3393. if (!extensions) {
  3394. return;
  3395. }
  3396. for (var i = 0; i < extensions.length; i++) {
  3397. var extension = extensions[i];
  3398. if (extension.enabled && action(extension)) {
  3399. return true;
  3400. }
  3401. }
  3402. return false;
  3403. };
  3404. return GLTFLoaderExtension;
  3405. }());
  3406. //
  3407. // Utilities
  3408. //
  3409. GLTFLoaderExtension._Extensions = [];
  3410. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  3411. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3412. })(BABYLON || (BABYLON = {}));
  3413. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  3414. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3415. var __extends = (this && this.__extends) || (function () {
  3416. var extendStatics = Object.setPrototypeOf ||
  3417. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  3418. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  3419. return function (d, b) {
  3420. extendStatics(d, b);
  3421. function __() { this.constructor = d; }
  3422. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3423. };
  3424. })();
  3425. var BABYLON;
  3426. (function (BABYLON) {
  3427. var GLTF2;
  3428. (function (GLTF2) {
  3429. var Extensions;
  3430. (function (Extensions) {
  3431. var MSFTLOD = (function (_super) {
  3432. __extends(MSFTLOD, _super);
  3433. function MSFTLOD() {
  3434. return _super !== null && _super.apply(this, arguments) || this;
  3435. }
  3436. Object.defineProperty(MSFTLOD.prototype, "name", {
  3437. get: function () {
  3438. return "MSFT_lod";
  3439. },
  3440. enumerable: true,
  3441. configurable: true
  3442. });
  3443. MSFTLOD.prototype.loadMaterial = function (loader, material, assign) {
  3444. if (!material.extensions) {
  3445. return false;
  3446. }
  3447. var properties = material.extensions[this.name];
  3448. if (!properties) {
  3449. return false;
  3450. }
  3451. // Clear out the extension so that it won't get loaded again.
  3452. material.extensions[this.name] = undefined;
  3453. // Tell the loader not to clear its state until the highest LOD is loaded.
  3454. loader.addLoaderPendingData(material);
  3455. // Start with the lowest quality LOD.
  3456. var materialLODs = [material.index].concat(properties.ids);
  3457. this.loadMaterialLOD(loader, material, materialLODs, materialLODs.length - 1, assign);
  3458. return true;
  3459. };
  3460. MSFTLOD.prototype.loadMaterialLOD = function (loader, material, materialLODs, lod, assign) {
  3461. var _this = this;
  3462. loader.loadMaterial(materialLODs[lod], function (babylonMaterial) {
  3463. babylonMaterial.name += ".LOD" + lod;
  3464. assign(babylonMaterial);
  3465. // Loading is complete if this is the highest quality LOD.
  3466. if (lod === 0) {
  3467. loader.removeLoaderPendingData(material);
  3468. return;
  3469. }
  3470. // Load the next LOD when all of the textures are loaded.
  3471. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  3472. _this.loadMaterialLOD(loader, material, materialLODs, lod - 1, assign);
  3473. });
  3474. });
  3475. };
  3476. return MSFTLOD;
  3477. }(GLTF2.GLTFLoaderExtension));
  3478. Extensions.MSFTLOD = MSFTLOD;
  3479. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  3480. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  3481. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3482. })(BABYLON || (BABYLON = {}));
  3483. //# sourceMappingURL=MSFT_lod.js.map
  3484. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3485. var __extends = (this && this.__extends) || (function () {
  3486. var extendStatics = Object.setPrototypeOf ||
  3487. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  3488. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  3489. return function (d, b) {
  3490. extendStatics(d, b);
  3491. function __() { this.constructor = d; }
  3492. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3493. };
  3494. })();
  3495. var BABYLON;
  3496. (function (BABYLON) {
  3497. var GLTF2;
  3498. (function (GLTF2) {
  3499. var Extensions;
  3500. (function (Extensions) {
  3501. var KHRMaterialsPbrSpecularGlossiness = (function (_super) {
  3502. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  3503. function KHRMaterialsPbrSpecularGlossiness() {
  3504. return _super !== null && _super.apply(this, arguments) || this;
  3505. }
  3506. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  3507. get: function () {
  3508. return "KHR_materials_pbrSpecularGlossiness";
  3509. },
  3510. enumerable: true,
  3511. configurable: true
  3512. });
  3513. KHRMaterialsPbrSpecularGlossiness.prototype.loadMaterial = function (loader, material, assign) {
  3514. if (!material.extensions) {
  3515. return false;
  3516. }
  3517. var properties = material.extensions[this.name];
  3518. if (!properties) {
  3519. return false;
  3520. }
  3521. loader.createPbrMaterial(material);
  3522. loader.loadMaterialBaseProperties(material);
  3523. material.babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  3524. material.babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  3525. material.babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  3526. if (properties.diffuseTexture) {
  3527. material.babylonMaterial.albedoTexture = loader.loadTexture(properties.diffuseTexture);
  3528. loader.loadMaterialAlphaProperties(material);
  3529. }
  3530. if (properties.specularGlossinessTexture) {
  3531. material.babylonMaterial.reflectivityTexture = loader.loadTexture(properties.specularGlossinessTexture);
  3532. material.babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  3533. }
  3534. assign(material.babylonMaterial);
  3535. return true;
  3536. };
  3537. return KHRMaterialsPbrSpecularGlossiness;
  3538. }(GLTF2.GLTFLoaderExtension));
  3539. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  3540. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  3541. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  3542. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3543. })(BABYLON || (BABYLON = {}));
  3544. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map