babylon.glTFFileLoader.js 179 KB

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