babylon.glTFFileLoader.js 203 KB

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