babylon.glTF1FileLoader.js 127 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. var GLTFLoaderCoordinateSystemMode;
  5. (function (GLTFLoaderCoordinateSystemMode) {
  6. /**
  7. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  8. */
  9. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  10. /**
  11. * Sets the useRightHandedSystem flag on the scene.
  12. */
  13. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  14. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  15. var GLTFLoaderAnimationStartMode;
  16. (function (GLTFLoaderAnimationStartMode) {
  17. /**
  18. * No animation will start.
  19. */
  20. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  21. /**
  22. * The first animation will start.
  23. */
  24. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  25. /**
  26. * All animations will start.
  27. */
  28. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  29. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  30. var GLTFLoaderState;
  31. (function (GLTFLoaderState) {
  32. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  33. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  34. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  35. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  36. var GLTFFileLoader = /** @class */ (function () {
  37. function GLTFFileLoader() {
  38. // #region Common options
  39. /**
  40. * Raised when the asset has been parsed.
  41. * The data.json property stores the glTF JSON.
  42. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  43. */
  44. this.onParsedObservable = new BABYLON.Observable();
  45. // #endregion
  46. // #region V2 options
  47. /**
  48. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  49. */
  50. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  51. /**
  52. * The animation start mode (NONE, FIRST, ALL).
  53. */
  54. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  55. /**
  56. * Set to true to compile materials before raising the success callback.
  57. */
  58. this.compileMaterials = false;
  59. /**
  60. * Set to true to also compile materials with clip planes.
  61. */
  62. this.useClipPlane = false;
  63. /**
  64. * Set to true to compile shadow generators before raising the success callback.
  65. */
  66. this.compileShadowGenerators = false;
  67. /**
  68. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  69. */
  70. this.onMeshLoadedObservable = new BABYLON.Observable();
  71. /**
  72. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  73. */
  74. this.onTextureLoadedObservable = new BABYLON.Observable();
  75. /**
  76. * Raised when the loader creates a material after parsing the glTF properties of the material.
  77. */
  78. this.onMaterialLoadedObservable = new BABYLON.Observable();
  79. /**
  80. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  81. * For assets with LODs, raised when all of the LODs are complete.
  82. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  83. */
  84. this.onCompleteObservable = new BABYLON.Observable();
  85. /**
  86. * Raised when the loader is disposed.
  87. */
  88. this.onDisposeObservable = new BABYLON.Observable();
  89. /**
  90. * Raised after a loader extension is created.
  91. * Set additional options for a loader extension in this event.
  92. */
  93. this.onExtensionLoadedObservable = new BABYLON.Observable();
  94. // #endregion
  95. this._loader = null;
  96. this.name = "gltf";
  97. this.extensions = {
  98. ".gltf": { isBinary: false },
  99. ".glb": { isBinary: true }
  100. };
  101. }
  102. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  103. set: function (callback) {
  104. if (this._onParsedObserver) {
  105. this.onParsedObservable.remove(this._onParsedObserver);
  106. }
  107. this._onParsedObserver = this.onParsedObservable.add(callback);
  108. },
  109. enumerable: true,
  110. configurable: true
  111. });
  112. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  113. set: function (callback) {
  114. if (this._onMeshLoadedObserver) {
  115. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  116. }
  117. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  118. },
  119. enumerable: true,
  120. configurable: true
  121. });
  122. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  123. set: function (callback) {
  124. if (this._onTextureLoadedObserver) {
  125. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  126. }
  127. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  128. },
  129. enumerable: true,
  130. configurable: true
  131. });
  132. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  133. set: function (callback) {
  134. if (this._onMaterialLoadedObserver) {
  135. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  136. }
  137. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  138. },
  139. enumerable: true,
  140. configurable: true
  141. });
  142. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  143. set: function (callback) {
  144. if (this._onCompleteObserver) {
  145. this.onCompleteObservable.remove(this._onCompleteObserver);
  146. }
  147. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  148. },
  149. enumerable: true,
  150. configurable: true
  151. });
  152. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  153. set: function (callback) {
  154. if (this._onDisposeObserver) {
  155. this.onDisposeObservable.remove(this._onDisposeObserver);
  156. }
  157. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  158. },
  159. enumerable: true,
  160. configurable: true
  161. });
  162. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  163. set: function (callback) {
  164. if (this._onExtensionLoadedObserver) {
  165. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  166. }
  167. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  168. },
  169. enumerable: true,
  170. configurable: true
  171. });
  172. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  173. /**
  174. * The loader state or null if not active.
  175. */
  176. get: function () {
  177. return this._loader ? this._loader.state : null;
  178. },
  179. enumerable: true,
  180. configurable: true
  181. });
  182. /**
  183. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  184. */
  185. GLTFFileLoader.prototype.dispose = function () {
  186. if (this._loader) {
  187. this._loader.dispose();
  188. this._loader = null;
  189. }
  190. this.onParsedObservable.clear();
  191. this.onMeshLoadedObservable.clear();
  192. this.onTextureLoadedObservable.clear();
  193. this.onMaterialLoadedObservable.clear();
  194. this.onCompleteObservable.clear();
  195. this.onDisposeObservable.notifyObservers(this);
  196. this.onDisposeObservable.clear();
  197. };
  198. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  199. var _this = this;
  200. return Promise.resolve().then(function () {
  201. var loaderData = _this._parse(data);
  202. _this._loader = _this._getLoader(loaderData);
  203. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  204. });
  205. };
  206. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  207. var _this = this;
  208. return Promise.resolve().then(function () {
  209. var loaderData = _this._parse(data);
  210. _this._loader = _this._getLoader(loaderData);
  211. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  212. });
  213. };
  214. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  215. var _this = this;
  216. return Promise.resolve().then(function () {
  217. var loaderData = _this._parse(data);
  218. _this._loader = _this._getLoader(loaderData);
  219. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  220. var container = new BABYLON.AssetContainer(scene);
  221. Array.prototype.push.apply(container.meshes, result.meshes);
  222. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  223. Array.prototype.push.apply(container.skeletons, result.skeletons);
  224. container.removeAllFromScene();
  225. return container;
  226. });
  227. });
  228. };
  229. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  230. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  231. };
  232. GLTFFileLoader.prototype.createPlugin = function () {
  233. return new GLTFFileLoader();
  234. };
  235. GLTFFileLoader.prototype._parse = function (data) {
  236. var parsedData;
  237. if (data instanceof ArrayBuffer) {
  238. parsedData = GLTFFileLoader._parseBinary(data);
  239. }
  240. else {
  241. parsedData = {
  242. json: JSON.parse(data),
  243. bin: null
  244. };
  245. }
  246. this.onParsedObservable.notifyObservers(parsedData);
  247. return parsedData;
  248. };
  249. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  250. var _this = this;
  251. var loaderVersion = { major: 2, minor: 0 };
  252. var asset = loaderData.json.asset || {};
  253. var version = GLTFFileLoader._parseVersion(asset.version);
  254. if (!version) {
  255. throw new Error("Invalid version: " + asset.version);
  256. }
  257. if (asset.minVersion !== undefined) {
  258. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  259. if (!minVersion) {
  260. throw new Error("Invalid minimum version: " + asset.minVersion);
  261. }
  262. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  263. throw new Error("Incompatible minimum version: " + asset.minVersion);
  264. }
  265. }
  266. var createLoaders = {
  267. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  268. 2: GLTFFileLoader.CreateGLTFLoaderV2
  269. };
  270. var createLoader = createLoaders[version.major];
  271. if (!createLoader) {
  272. throw new Error("Unsupported version: " + asset.version);
  273. }
  274. var loader = createLoader();
  275. loader.coordinateSystemMode = this.coordinateSystemMode;
  276. loader.animationStartMode = this.animationStartMode;
  277. loader.compileMaterials = this.compileMaterials;
  278. loader.useClipPlane = this.useClipPlane;
  279. loader.compileShadowGenerators = this.compileShadowGenerators;
  280. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  281. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  282. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  283. loader.onCompleteObservable.add(function () { return _this.onCompleteObservable.notifyObservers(_this); });
  284. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  285. return loader;
  286. };
  287. GLTFFileLoader._parseBinary = function (data) {
  288. var Binary = {
  289. Magic: 0x46546C67
  290. };
  291. var binaryReader = new BinaryReader(data);
  292. var magic = binaryReader.readUint32();
  293. if (magic !== Binary.Magic) {
  294. throw new Error("Unexpected magic: " + magic);
  295. }
  296. var version = binaryReader.readUint32();
  297. switch (version) {
  298. case 1: return GLTFFileLoader._parseV1(binaryReader);
  299. case 2: return GLTFFileLoader._parseV2(binaryReader);
  300. }
  301. throw new Error("Unsupported version: " + version);
  302. };
  303. GLTFFileLoader._parseV1 = function (binaryReader) {
  304. var ContentFormat = {
  305. JSON: 0
  306. };
  307. var length = binaryReader.readUint32();
  308. if (length != binaryReader.getLength()) {
  309. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  310. }
  311. var contentLength = binaryReader.readUint32();
  312. var contentFormat = binaryReader.readUint32();
  313. var content;
  314. switch (contentFormat) {
  315. case ContentFormat.JSON: {
  316. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  317. break;
  318. }
  319. default: {
  320. throw new Error("Unexpected content format: " + contentFormat);
  321. }
  322. }
  323. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  324. var body = binaryReader.readUint8Array(bytesRemaining);
  325. return {
  326. json: content,
  327. bin: body
  328. };
  329. };
  330. GLTFFileLoader._parseV2 = function (binaryReader) {
  331. var ChunkFormat = {
  332. JSON: 0x4E4F534A,
  333. BIN: 0x004E4942
  334. };
  335. var length = binaryReader.readUint32();
  336. if (length !== binaryReader.getLength()) {
  337. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  338. }
  339. // JSON chunk
  340. var chunkLength = binaryReader.readUint32();
  341. var chunkFormat = binaryReader.readUint32();
  342. if (chunkFormat !== ChunkFormat.JSON) {
  343. throw new Error("First chunk format is not JSON");
  344. }
  345. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  346. // Look for BIN chunk
  347. var bin = null;
  348. while (binaryReader.getPosition() < binaryReader.getLength()) {
  349. var chunkLength_1 = binaryReader.readUint32();
  350. var chunkFormat_1 = binaryReader.readUint32();
  351. switch (chunkFormat_1) {
  352. case ChunkFormat.JSON: {
  353. throw new Error("Unexpected JSON chunk");
  354. }
  355. case ChunkFormat.BIN: {
  356. bin = binaryReader.readUint8Array(chunkLength_1);
  357. break;
  358. }
  359. default: {
  360. // ignore unrecognized chunkFormat
  361. binaryReader.skipBytes(chunkLength_1);
  362. break;
  363. }
  364. }
  365. }
  366. return {
  367. json: json,
  368. bin: bin
  369. };
  370. };
  371. GLTFFileLoader._parseVersion = function (version) {
  372. if (version === "1.0" || version === "1.0.1") {
  373. return {
  374. major: 1,
  375. minor: 0
  376. };
  377. }
  378. var match = (version + "").match(/^(\d+)\.(\d+)/);
  379. if (!match) {
  380. return null;
  381. }
  382. return {
  383. major: parseInt(match[1]),
  384. minor: parseInt(match[2])
  385. };
  386. };
  387. GLTFFileLoader._compareVersion = function (a, b) {
  388. if (a.major > b.major)
  389. return 1;
  390. if (a.major < b.major)
  391. return -1;
  392. if (a.minor > b.minor)
  393. return 1;
  394. if (a.minor < b.minor)
  395. return -1;
  396. return 0;
  397. };
  398. GLTFFileLoader._decodeBufferToText = function (buffer) {
  399. var result = "";
  400. var length = buffer.byteLength;
  401. for (var i = 0; i < length; i++) {
  402. result += String.fromCharCode(buffer[i]);
  403. }
  404. return result;
  405. };
  406. // #endregion
  407. // #region V1 options
  408. GLTFFileLoader.IncrementalLoading = true;
  409. GLTFFileLoader.HomogeneousCoordinates = false;
  410. return GLTFFileLoader;
  411. }());
  412. BABYLON.GLTFFileLoader = GLTFFileLoader;
  413. var BinaryReader = /** @class */ (function () {
  414. function BinaryReader(arrayBuffer) {
  415. this._arrayBuffer = arrayBuffer;
  416. this._dataView = new DataView(arrayBuffer);
  417. this._byteOffset = 0;
  418. }
  419. BinaryReader.prototype.getPosition = function () {
  420. return this._byteOffset;
  421. };
  422. BinaryReader.prototype.getLength = function () {
  423. return this._arrayBuffer.byteLength;
  424. };
  425. BinaryReader.prototype.readUint32 = function () {
  426. var value = this._dataView.getUint32(this._byteOffset, true);
  427. this._byteOffset += 4;
  428. return value;
  429. };
  430. BinaryReader.prototype.readUint8Array = function (length) {
  431. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  432. this._byteOffset += length;
  433. return value;
  434. };
  435. BinaryReader.prototype.skipBytes = function (length) {
  436. this._byteOffset += length;
  437. };
  438. return BinaryReader;
  439. }());
  440. if (BABYLON.SceneLoader) {
  441. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  442. }
  443. })(BABYLON || (BABYLON = {}));
  444. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  445. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  446. var BABYLON;
  447. (function (BABYLON) {
  448. var GLTF1;
  449. (function (GLTF1) {
  450. /**
  451. * Enums
  452. */
  453. var EComponentType;
  454. (function (EComponentType) {
  455. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  456. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  457. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  458. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  459. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  460. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  461. var EShaderType;
  462. (function (EShaderType) {
  463. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  464. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  465. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  466. var EParameterType;
  467. (function (EParameterType) {
  468. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  469. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  470. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  471. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  472. EParameterType[EParameterType["INT"] = 5124] = "INT";
  473. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  474. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  475. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  476. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  477. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  478. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  479. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  480. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  481. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  482. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  483. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  484. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  485. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  486. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  487. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  488. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  489. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  490. var ETextureWrapMode;
  491. (function (ETextureWrapMode) {
  492. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  493. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  494. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  495. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  496. var ETextureFilterType;
  497. (function (ETextureFilterType) {
  498. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  499. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  500. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  501. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  502. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  503. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  504. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  505. var ETextureFormat;
  506. (function (ETextureFormat) {
  507. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  508. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  509. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  510. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  511. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  512. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  513. var ECullingType;
  514. (function (ECullingType) {
  515. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  516. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  517. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  518. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  519. var EBlendingFunction;
  520. (function (EBlendingFunction) {
  521. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  522. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  523. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  524. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  525. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  526. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  527. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  528. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  529. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  530. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  531. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  532. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  533. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  534. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  535. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  536. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  537. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  538. })(BABYLON || (BABYLON = {}));
  539. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  540. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  541. var BABYLON;
  542. (function (BABYLON) {
  543. var GLTF1;
  544. (function (GLTF1) {
  545. /**
  546. * Tokenizer. Used for shaders compatibility
  547. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  548. */
  549. var ETokenType;
  550. (function (ETokenType) {
  551. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  552. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  553. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  554. })(ETokenType || (ETokenType = {}));
  555. var Tokenizer = /** @class */ (function () {
  556. function Tokenizer(toParse) {
  557. this._pos = 0;
  558. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  559. this._toParse = toParse;
  560. this._maxPos = toParse.length;
  561. }
  562. Tokenizer.prototype.getNextToken = function () {
  563. if (this.isEnd())
  564. return ETokenType.END_OF_INPUT;
  565. this.currentString = this.read();
  566. this.currentToken = ETokenType.UNKNOWN;
  567. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  568. this.currentToken = ETokenType.IDENTIFIER;
  569. this.currentIdentifier = this.currentString;
  570. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  571. this.currentIdentifier += this.currentString;
  572. this.forward();
  573. }
  574. }
  575. return this.currentToken;
  576. };
  577. Tokenizer.prototype.peek = function () {
  578. return this._toParse[this._pos];
  579. };
  580. Tokenizer.prototype.read = function () {
  581. return this._toParse[this._pos++];
  582. };
  583. Tokenizer.prototype.forward = function () {
  584. this._pos++;
  585. };
  586. Tokenizer.prototype.isEnd = function () {
  587. return this._pos >= this._maxPos;
  588. };
  589. return Tokenizer;
  590. }());
  591. /**
  592. * Values
  593. */
  594. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  595. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  596. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  597. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  598. /**
  599. * Parse
  600. */
  601. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  602. for (var buf in parsedBuffers) {
  603. var parsedBuffer = parsedBuffers[buf];
  604. gltfRuntime.buffers[buf] = parsedBuffer;
  605. gltfRuntime.buffersCount++;
  606. }
  607. };
  608. var parseShaders = function (parsedShaders, gltfRuntime) {
  609. for (var sha in parsedShaders) {
  610. var parsedShader = parsedShaders[sha];
  611. gltfRuntime.shaders[sha] = parsedShader;
  612. gltfRuntime.shaderscount++;
  613. }
  614. };
  615. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  616. for (var object in parsedObjects) {
  617. var parsedObject = parsedObjects[object];
  618. gltfRuntime[runtimeProperty][object] = parsedObject;
  619. }
  620. };
  621. /**
  622. * Utils
  623. */
  624. var normalizeUVs = function (buffer) {
  625. if (!buffer) {
  626. return;
  627. }
  628. for (var i = 0; i < buffer.length / 2; i++) {
  629. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  630. }
  631. };
  632. var getAttribute = function (attributeParameter) {
  633. if (attributeParameter.semantic === "NORMAL") {
  634. return "normal";
  635. }
  636. else if (attributeParameter.semantic === "POSITION") {
  637. return "position";
  638. }
  639. else if (attributeParameter.semantic === "JOINT") {
  640. return "matricesIndices";
  641. }
  642. else if (attributeParameter.semantic === "WEIGHT") {
  643. return "matricesWeights";
  644. }
  645. else if (attributeParameter.semantic === "COLOR") {
  646. return "color";
  647. }
  648. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  649. var channel = Number(attributeParameter.semantic.split("_")[1]);
  650. return "uv" + (channel === 0 ? "" : channel + 1);
  651. }
  652. return null;
  653. };
  654. /**
  655. * Loads and creates animations
  656. */
  657. var loadAnimations = function (gltfRuntime) {
  658. for (var anim in gltfRuntime.animations) {
  659. var animation = gltfRuntime.animations[anim];
  660. if (!animation.channels || !animation.samplers) {
  661. continue;
  662. }
  663. var lastAnimation = null;
  664. for (var i = 0; i < animation.channels.length; i++) {
  665. // Get parameters and load buffers
  666. var channel = animation.channels[i];
  667. var sampler = animation.samplers[channel.sampler];
  668. if (!sampler) {
  669. continue;
  670. }
  671. var inputData = null;
  672. var outputData = null;
  673. if (animation.parameters) {
  674. inputData = animation.parameters[sampler.input];
  675. outputData = animation.parameters[sampler.output];
  676. }
  677. else {
  678. inputData = sampler.input;
  679. outputData = sampler.output;
  680. }
  681. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  682. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  683. var targetID = channel.target.id;
  684. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  685. if (targetNode === null) {
  686. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  687. }
  688. if (targetNode === null) {
  689. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  690. continue;
  691. }
  692. var isBone = targetNode instanceof BABYLON.Bone;
  693. // Get target path (position, rotation or scaling)
  694. var targetPath = channel.target.path;
  695. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  696. if (targetPathIndex !== -1) {
  697. targetPath = babylonAnimationPaths[targetPathIndex];
  698. }
  699. // Determine animation type
  700. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  701. if (!isBone) {
  702. if (targetPath === "rotationQuaternion") {
  703. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  704. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  705. }
  706. else {
  707. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  708. }
  709. }
  710. // Create animation and key frames
  711. var babylonAnimation = null;
  712. var keys = [];
  713. var arrayOffset = 0;
  714. var modifyKey = false;
  715. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  716. babylonAnimation = lastAnimation;
  717. modifyKey = true;
  718. }
  719. if (!modifyKey) {
  720. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  721. }
  722. // For each frame
  723. for (var j = 0; j < bufferInput.length; j++) {
  724. var value = null;
  725. if (targetPath === "rotationQuaternion") {
  726. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  727. arrayOffset += 4;
  728. }
  729. else {
  730. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  731. arrayOffset += 3;
  732. }
  733. if (isBone) {
  734. var bone = targetNode;
  735. var translation = BABYLON.Vector3.Zero();
  736. var rotationQuaternion = new BABYLON.Quaternion();
  737. var scaling = BABYLON.Vector3.Zero();
  738. // Warning on decompose
  739. var mat = bone.getBaseMatrix();
  740. if (modifyKey && lastAnimation) {
  741. mat = lastAnimation.getKeys()[j].value;
  742. }
  743. mat.decompose(scaling, rotationQuaternion, translation);
  744. if (targetPath === "position") {
  745. translation = value;
  746. }
  747. else if (targetPath === "rotationQuaternion") {
  748. rotationQuaternion = value;
  749. }
  750. else {
  751. scaling = value;
  752. }
  753. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  754. }
  755. if (!modifyKey) {
  756. keys.push({
  757. frame: bufferInput[j],
  758. value: value
  759. });
  760. }
  761. else if (lastAnimation) {
  762. lastAnimation.getKeys()[j].value = value;
  763. }
  764. }
  765. // Finish
  766. if (!modifyKey && babylonAnimation) {
  767. babylonAnimation.setKeys(keys);
  768. targetNode.animations.push(babylonAnimation);
  769. }
  770. lastAnimation = babylonAnimation;
  771. gltfRuntime.scene.stopAnimation(targetNode);
  772. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  773. }
  774. }
  775. };
  776. /**
  777. * Returns the bones transformation matrix
  778. */
  779. var configureBoneTransformation = function (node) {
  780. var mat = null;
  781. if (node.translation || node.rotation || node.scale) {
  782. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  783. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  784. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  785. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  786. }
  787. else {
  788. mat = BABYLON.Matrix.FromArray(node.matrix);
  789. }
  790. return mat;
  791. };
  792. /**
  793. * Returns the parent bone
  794. */
  795. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  796. // Try to find
  797. for (var i = 0; i < newSkeleton.bones.length; i++) {
  798. if (newSkeleton.bones[i].name === jointName) {
  799. return newSkeleton.bones[i];
  800. }
  801. }
  802. // Not found, search in gltf nodes
  803. var nodes = gltfRuntime.nodes;
  804. for (var nde in nodes) {
  805. var node = nodes[nde];
  806. if (!node.jointName) {
  807. continue;
  808. }
  809. var children = node.children;
  810. for (var i = 0; i < children.length; i++) {
  811. var child = gltfRuntime.nodes[children[i]];
  812. if (!child.jointName) {
  813. continue;
  814. }
  815. if (child.jointName === jointName) {
  816. var mat = configureBoneTransformation(node);
  817. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  818. bone.id = nde;
  819. return bone;
  820. }
  821. }
  822. }
  823. return null;
  824. };
  825. /**
  826. * Returns the appropriate root node
  827. */
  828. var getNodeToRoot = function (nodesToRoot, id) {
  829. for (var i = 0; i < nodesToRoot.length; i++) {
  830. var nodeToRoot = nodesToRoot[i];
  831. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  832. var child = nodeToRoot.node.children[j];
  833. if (child === id) {
  834. return nodeToRoot.bone;
  835. }
  836. }
  837. }
  838. return null;
  839. };
  840. /**
  841. * Returns the node with the joint name
  842. */
  843. var getJointNode = function (gltfRuntime, jointName) {
  844. var nodes = gltfRuntime.nodes;
  845. var node = nodes[jointName];
  846. if (node) {
  847. return {
  848. node: node,
  849. id: jointName
  850. };
  851. }
  852. for (var nde in nodes) {
  853. node = nodes[nde];
  854. if (node.jointName === jointName) {
  855. return {
  856. node: node,
  857. id: nde
  858. };
  859. }
  860. }
  861. return null;
  862. };
  863. /**
  864. * Checks if a nodes is in joints
  865. */
  866. var nodeIsInJoints = function (skins, id) {
  867. for (var i = 0; i < skins.jointNames.length; i++) {
  868. if (skins.jointNames[i] === id) {
  869. return true;
  870. }
  871. }
  872. return false;
  873. };
  874. /**
  875. * Fills the nodes to root for bones and builds hierarchy
  876. */
  877. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  878. // Creates nodes for root
  879. for (var nde in gltfRuntime.nodes) {
  880. var node = gltfRuntime.nodes[nde];
  881. var id = nde;
  882. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  883. continue;
  884. }
  885. // Create node to root bone
  886. var mat = configureBoneTransformation(node);
  887. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  888. bone.id = id;
  889. nodesToRoot.push({ bone: bone, node: node, id: id });
  890. }
  891. // Parenting
  892. for (var i = 0; i < nodesToRoot.length; i++) {
  893. var nodeToRoot = nodesToRoot[i];
  894. var children = nodeToRoot.node.children;
  895. for (var j = 0; j < children.length; j++) {
  896. var child = null;
  897. for (var k = 0; k < nodesToRoot.length; k++) {
  898. if (nodesToRoot[k].id === children[j]) {
  899. child = nodesToRoot[k];
  900. break;
  901. }
  902. }
  903. if (child) {
  904. child.bone._parent = nodeToRoot.bone;
  905. nodeToRoot.bone.children.push(child.bone);
  906. }
  907. }
  908. }
  909. };
  910. /**
  911. * Imports a skeleton
  912. */
  913. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  914. if (!newSkeleton) {
  915. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  916. }
  917. if (!skins.babylonSkeleton) {
  918. return newSkeleton;
  919. }
  920. // Find the root bones
  921. var nodesToRoot = [];
  922. var nodesToRootToAdd = [];
  923. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  924. newSkeleton.bones = [];
  925. // Joints
  926. for (var i = 0; i < skins.jointNames.length; i++) {
  927. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  928. if (!jointNode) {
  929. continue;
  930. }
  931. var node = jointNode.node;
  932. if (!node) {
  933. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  934. continue;
  935. }
  936. var id = jointNode.id;
  937. // Optimize, if the bone already exists...
  938. var existingBone = gltfRuntime.scene.getBoneByID(id);
  939. if (existingBone) {
  940. newSkeleton.bones.push(existingBone);
  941. continue;
  942. }
  943. // Search for parent bone
  944. var foundBone = false;
  945. var parentBone = null;
  946. for (var j = 0; j < i; j++) {
  947. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  948. if (!jointNode_1) {
  949. continue;
  950. }
  951. var joint = jointNode_1.node;
  952. if (!joint) {
  953. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  954. continue;
  955. }
  956. var children = joint.children;
  957. if (!children) {
  958. continue;
  959. }
  960. foundBone = false;
  961. for (var k = 0; k < children.length; k++) {
  962. if (children[k] === id) {
  963. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  964. foundBone = true;
  965. break;
  966. }
  967. }
  968. if (foundBone) {
  969. break;
  970. }
  971. }
  972. // Create bone
  973. var mat = configureBoneTransformation(node);
  974. if (!parentBone && nodesToRoot.length > 0) {
  975. parentBone = getNodeToRoot(nodesToRoot, id);
  976. if (parentBone) {
  977. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  978. nodesToRootToAdd.push(parentBone);
  979. }
  980. }
  981. }
  982. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  983. bone.id = id;
  984. }
  985. // Polish
  986. var bones = newSkeleton.bones;
  987. newSkeleton.bones = [];
  988. for (var i = 0; i < skins.jointNames.length; i++) {
  989. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  990. if (!jointNode) {
  991. continue;
  992. }
  993. for (var j = 0; j < bones.length; j++) {
  994. if (bones[j].id === jointNode.id) {
  995. newSkeleton.bones.push(bones[j]);
  996. break;
  997. }
  998. }
  999. }
  1000. newSkeleton.prepare();
  1001. // Finish
  1002. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  1003. newSkeleton.bones.push(nodesToRootToAdd[i]);
  1004. }
  1005. return newSkeleton;
  1006. };
  1007. /**
  1008. * Imports a mesh and its geometries
  1009. */
  1010. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  1011. if (!newMesh) {
  1012. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1013. newMesh.id = id;
  1014. }
  1015. if (!node.babylonNode) {
  1016. return newMesh;
  1017. }
  1018. var subMaterials = [];
  1019. var vertexData = null;
  1020. var verticesStarts = new Array();
  1021. var verticesCounts = new Array();
  1022. var indexStarts = new Array();
  1023. var indexCounts = new Array();
  1024. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1025. var meshID = meshes[meshIndex];
  1026. var mesh = gltfRuntime.meshes[meshID];
  1027. if (!mesh) {
  1028. continue;
  1029. }
  1030. // Positions, normals and UVs
  1031. for (var i = 0; i < mesh.primitives.length; i++) {
  1032. // Temporary vertex data
  1033. var tempVertexData = new BABYLON.VertexData();
  1034. var primitive = mesh.primitives[i];
  1035. if (primitive.mode !== 4) {
  1036. // continue;
  1037. }
  1038. var attributes = primitive.attributes;
  1039. var accessor = null;
  1040. var buffer = null;
  1041. // Set positions, normal and uvs
  1042. for (var semantic in attributes) {
  1043. // Link accessor and buffer view
  1044. accessor = gltfRuntime.accessors[attributes[semantic]];
  1045. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1046. if (semantic === "NORMAL") {
  1047. tempVertexData.normals = new Float32Array(buffer.length);
  1048. tempVertexData.normals.set(buffer);
  1049. }
  1050. else if (semantic === "POSITION") {
  1051. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  1052. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  1053. for (var j = 0; j < buffer.length; j += 4) {
  1054. tempVertexData.positions[j] = buffer[j];
  1055. tempVertexData.positions[j + 1] = buffer[j + 1];
  1056. tempVertexData.positions[j + 2] = buffer[j + 2];
  1057. }
  1058. }
  1059. else {
  1060. tempVertexData.positions = new Float32Array(buffer.length);
  1061. tempVertexData.positions.set(buffer);
  1062. }
  1063. verticesCounts.push(tempVertexData.positions.length);
  1064. }
  1065. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  1066. var channel = Number(semantic.split("_")[1]);
  1067. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  1068. var uvs = new Float32Array(buffer.length);
  1069. uvs.set(buffer);
  1070. normalizeUVs(uvs);
  1071. tempVertexData.set(uvs, uvKind);
  1072. }
  1073. else if (semantic === "JOINT") {
  1074. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  1075. tempVertexData.matricesIndices.set(buffer);
  1076. }
  1077. else if (semantic === "WEIGHT") {
  1078. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  1079. tempVertexData.matricesWeights.set(buffer);
  1080. }
  1081. else if (semantic === "COLOR") {
  1082. tempVertexData.colors = new Float32Array(buffer.length);
  1083. tempVertexData.colors.set(buffer);
  1084. }
  1085. }
  1086. // Indices
  1087. accessor = gltfRuntime.accessors[primitive.indices];
  1088. if (accessor) {
  1089. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1090. tempVertexData.indices = new Int32Array(buffer.length);
  1091. tempVertexData.indices.set(buffer);
  1092. indexCounts.push(tempVertexData.indices.length);
  1093. }
  1094. else {
  1095. // Set indices on the fly
  1096. var indices = [];
  1097. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  1098. indices.push(j);
  1099. }
  1100. tempVertexData.indices = new Int32Array(indices);
  1101. indexCounts.push(tempVertexData.indices.length);
  1102. }
  1103. if (!vertexData) {
  1104. vertexData = tempVertexData;
  1105. }
  1106. else {
  1107. vertexData.merge(tempVertexData);
  1108. }
  1109. // Sub material
  1110. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  1111. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  1112. // Update vertices start and index start
  1113. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  1114. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  1115. }
  1116. }
  1117. var material;
  1118. if (subMaterials.length > 1) {
  1119. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  1120. material.subMaterials = subMaterials;
  1121. }
  1122. else {
  1123. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  1124. }
  1125. if (subMaterials.length === 1) {
  1126. material = subMaterials[0];
  1127. }
  1128. if (!newMesh.material) {
  1129. newMesh.material = material;
  1130. }
  1131. // Apply geometry
  1132. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  1133. newMesh.computeWorldMatrix(true);
  1134. // Apply submeshes
  1135. newMesh.subMeshes = [];
  1136. var index = 0;
  1137. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1138. var meshID = meshes[meshIndex];
  1139. var mesh = gltfRuntime.meshes[meshID];
  1140. if (!mesh) {
  1141. continue;
  1142. }
  1143. for (var i = 0; i < mesh.primitives.length; i++) {
  1144. if (mesh.primitives[i].mode !== 4) {
  1145. //continue;
  1146. }
  1147. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  1148. index++;
  1149. }
  1150. }
  1151. // Finish
  1152. return newMesh;
  1153. };
  1154. /**
  1155. * Configure node transformation from position, rotation and scaling
  1156. */
  1157. var configureNode = function (newNode, position, rotation, scaling) {
  1158. if (newNode.position) {
  1159. newNode.position = position;
  1160. }
  1161. if (newNode.rotationQuaternion || newNode.rotation) {
  1162. newNode.rotationQuaternion = rotation;
  1163. }
  1164. if (newNode.scaling) {
  1165. newNode.scaling = scaling;
  1166. }
  1167. };
  1168. /**
  1169. * Configures node from transformation matrix
  1170. */
  1171. var configureNodeFromMatrix = function (newNode, node, parent) {
  1172. if (node.matrix) {
  1173. var position = new BABYLON.Vector3(0, 0, 0);
  1174. var rotation = new BABYLON.Quaternion();
  1175. var scaling = new BABYLON.Vector3(0, 0, 0);
  1176. var mat = BABYLON.Matrix.FromArray(node.matrix);
  1177. mat.decompose(scaling, rotation, position);
  1178. configureNode(newNode, position, rotation, scaling);
  1179. }
  1180. else if (node.translation && node.rotation && node.scale) {
  1181. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  1182. }
  1183. newNode.computeWorldMatrix(true);
  1184. };
  1185. /**
  1186. * Imports a node
  1187. */
  1188. var importNode = function (gltfRuntime, node, id, parent) {
  1189. var lastNode = null;
  1190. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  1191. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  1192. return null;
  1193. }
  1194. }
  1195. // Meshes
  1196. if (node.skin) {
  1197. if (node.meshes) {
  1198. var skin = gltfRuntime.skins[node.skin];
  1199. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  1200. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  1201. if (newMesh.skeleton === null) {
  1202. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  1203. if (!skin.babylonSkeleton) {
  1204. skin.babylonSkeleton = newMesh.skeleton;
  1205. }
  1206. }
  1207. lastNode = newMesh;
  1208. }
  1209. }
  1210. else if (node.meshes) {
  1211. /**
  1212. * Improve meshes property
  1213. */
  1214. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  1215. lastNode = newMesh;
  1216. }
  1217. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1218. var light = gltfRuntime.lights[node.light];
  1219. if (light) {
  1220. if (light.type === "ambient") {
  1221. var ambienLight = light[light.type];
  1222. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1223. hemiLight.name = node.name || "";
  1224. if (ambienLight.color) {
  1225. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  1226. }
  1227. lastNode = hemiLight;
  1228. }
  1229. else if (light.type === "directional") {
  1230. var directionalLight = light[light.type];
  1231. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1232. dirLight.name = node.name || "";
  1233. if (directionalLight.color) {
  1234. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  1235. }
  1236. lastNode = dirLight;
  1237. }
  1238. else if (light.type === "point") {
  1239. var pointLight = light[light.type];
  1240. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1241. ptLight.name = node.name || "";
  1242. if (pointLight.color) {
  1243. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  1244. }
  1245. lastNode = ptLight;
  1246. }
  1247. else if (light.type === "spot") {
  1248. var spotLight = light[light.type];
  1249. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  1250. spLight.name = node.name || "";
  1251. if (spotLight.color) {
  1252. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  1253. }
  1254. if (spotLight.fallOfAngle) {
  1255. spLight.angle = spotLight.fallOfAngle;
  1256. }
  1257. if (spotLight.fallOffExponent) {
  1258. spLight.exponent = spotLight.fallOffExponent;
  1259. }
  1260. lastNode = spLight;
  1261. }
  1262. }
  1263. }
  1264. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1265. var camera = gltfRuntime.cameras[node.camera];
  1266. if (camera) {
  1267. if (camera.type === "orthographic") {
  1268. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1269. orthoCamera.name = node.name || "";
  1270. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  1271. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1272. lastNode = orthoCamera;
  1273. }
  1274. else if (camera.type === "perspective") {
  1275. var perspectiveCamera = camera[camera.type];
  1276. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1277. persCamera.name = node.name || "";
  1278. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1279. if (!perspectiveCamera.aspectRatio) {
  1280. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  1281. }
  1282. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  1283. persCamera.maxZ = perspectiveCamera.zfar;
  1284. persCamera.minZ = perspectiveCamera.znear;
  1285. }
  1286. lastNode = persCamera;
  1287. }
  1288. }
  1289. }
  1290. // Empty node
  1291. if (!node.jointName) {
  1292. if (node.babylonNode) {
  1293. return node.babylonNode;
  1294. }
  1295. else if (lastNode === null) {
  1296. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1297. node.babylonNode = dummy;
  1298. lastNode = dummy;
  1299. }
  1300. }
  1301. if (lastNode !== null) {
  1302. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  1303. configureNodeFromMatrix(lastNode, node, parent);
  1304. }
  1305. else {
  1306. var translation = node.translation || [0, 0, 0];
  1307. var rotation = node.rotation || [0, 0, 0, 1];
  1308. var scale = node.scale || [1, 1, 1];
  1309. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  1310. }
  1311. lastNode.updateCache(true);
  1312. node.babylonNode = lastNode;
  1313. }
  1314. return lastNode;
  1315. };
  1316. /**
  1317. * Traverses nodes and creates them
  1318. */
  1319. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  1320. if (meshIncluded === void 0) { meshIncluded = false; }
  1321. var node = gltfRuntime.nodes[id];
  1322. var newNode = null;
  1323. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  1324. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  1325. meshIncluded = true;
  1326. }
  1327. else {
  1328. meshIncluded = false;
  1329. }
  1330. }
  1331. else {
  1332. meshIncluded = true;
  1333. }
  1334. if (!node.jointName && meshIncluded) {
  1335. newNode = importNode(gltfRuntime, node, id, parent);
  1336. if (newNode !== null) {
  1337. newNode.id = id;
  1338. newNode.parent = parent;
  1339. }
  1340. }
  1341. if (node.children) {
  1342. for (var i = 0; i < node.children.length; i++) {
  1343. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  1344. }
  1345. }
  1346. };
  1347. /**
  1348. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  1349. */
  1350. var postLoad = function (gltfRuntime) {
  1351. // Nodes
  1352. var currentScene = gltfRuntime.currentScene;
  1353. if (currentScene) {
  1354. for (var i = 0; i < currentScene.nodes.length; i++) {
  1355. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1356. }
  1357. }
  1358. else {
  1359. for (var thing in gltfRuntime.scenes) {
  1360. currentScene = gltfRuntime.scenes[thing];
  1361. for (var i = 0; i < currentScene.nodes.length; i++) {
  1362. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1363. }
  1364. }
  1365. }
  1366. // Set animations
  1367. loadAnimations(gltfRuntime);
  1368. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  1369. var skeleton = gltfRuntime.scene.skeletons[i];
  1370. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  1371. }
  1372. };
  1373. /**
  1374. * onBind shaderrs callback to set uniforms and matrices
  1375. */
  1376. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  1377. var materialValues = material.values || technique.parameters;
  1378. for (var unif in unTreatedUniforms) {
  1379. var uniform = unTreatedUniforms[unif];
  1380. var type = uniform.type;
  1381. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  1382. if (uniform.semantic && !uniform.source && !uniform.node) {
  1383. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1384. }
  1385. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1386. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  1387. if (source === null) {
  1388. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  1389. }
  1390. if (source === null) {
  1391. continue;
  1392. }
  1393. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1394. }
  1395. }
  1396. else {
  1397. var value = materialValues[technique.uniforms[unif]];
  1398. if (!value) {
  1399. continue;
  1400. }
  1401. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1402. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  1403. if (texture === null || texture === undefined) {
  1404. continue;
  1405. }
  1406. shaderMaterial.getEffect().setTexture(unif, texture);
  1407. }
  1408. else {
  1409. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  1410. }
  1411. }
  1412. }
  1413. onSuccess(shaderMaterial);
  1414. };
  1415. /**
  1416. * Prepare uniforms to send the only one time
  1417. * Loads the appropriate textures
  1418. */
  1419. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1420. var materialValues = material.values || technique.parameters;
  1421. var techniqueUniforms = technique.uniforms;
  1422. /**
  1423. * Prepare values here (not matrices)
  1424. */
  1425. for (var unif in unTreatedUniforms) {
  1426. var uniform = unTreatedUniforms[unif];
  1427. var type = uniform.type;
  1428. var value = materialValues[techniqueUniforms[unif]];
  1429. if (value === undefined) {
  1430. // In case the value is the same for all materials
  1431. value = uniform.value;
  1432. }
  1433. if (!value) {
  1434. continue;
  1435. }
  1436. var onLoadTexture = function (uniformName) {
  1437. return function (texture) {
  1438. if (uniform.value && uniformName) {
  1439. // Static uniform
  1440. shaderMaterial.setTexture(uniformName, texture);
  1441. delete unTreatedUniforms[uniformName];
  1442. }
  1443. };
  1444. };
  1445. // Texture (sampler2D)
  1446. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1447. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  1448. }
  1449. else {
  1450. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  1451. // Static uniform
  1452. delete unTreatedUniforms[unif];
  1453. }
  1454. }
  1455. }
  1456. };
  1457. /**
  1458. * Shader compilation failed
  1459. */
  1460. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1461. return function (effect, error) {
  1462. shaderMaterial.dispose(true);
  1463. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1464. };
  1465. };
  1466. /**
  1467. * Shader compilation success
  1468. */
  1469. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1470. return function (_) {
  1471. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1472. shaderMaterial.onBind = function (mesh) {
  1473. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1474. };
  1475. };
  1476. };
  1477. /**
  1478. * Returns the appropriate uniform if already handled by babylon
  1479. */
  1480. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1481. for (var unif in technique.uniforms) {
  1482. var uniform = technique.uniforms[unif];
  1483. var uniformParameter = technique.parameters[uniform];
  1484. if (tokenizer.currentIdentifier === unif) {
  1485. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1486. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1487. if (transformIndex !== -1) {
  1488. delete unTreatedUniforms[unif];
  1489. return babylonTransforms[transformIndex];
  1490. }
  1491. }
  1492. }
  1493. }
  1494. return tokenizer.currentIdentifier;
  1495. };
  1496. /**
  1497. * All shaders loaded. Create materials one by one
  1498. */
  1499. var importMaterials = function (gltfRuntime) {
  1500. // Create materials
  1501. for (var mat in gltfRuntime.materials) {
  1502. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1503. }
  1504. };
  1505. /**
  1506. * Implementation of the base glTF spec
  1507. */
  1508. var GLTFLoaderBase = /** @class */ (function () {
  1509. function GLTFLoaderBase() {
  1510. }
  1511. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1512. var gltfRuntime = {
  1513. extensions: {},
  1514. accessors: {},
  1515. buffers: {},
  1516. bufferViews: {},
  1517. meshes: {},
  1518. lights: {},
  1519. cameras: {},
  1520. nodes: {},
  1521. images: {},
  1522. textures: {},
  1523. shaders: {},
  1524. programs: {},
  1525. samplers: {},
  1526. techniques: {},
  1527. materials: {},
  1528. animations: {},
  1529. skins: {},
  1530. extensionsUsed: [],
  1531. scenes: {},
  1532. buffersCount: 0,
  1533. shaderscount: 0,
  1534. scene: scene,
  1535. rootUrl: rootUrl,
  1536. loadedBufferCount: 0,
  1537. loadedBufferViews: {},
  1538. loadedShaderCount: 0,
  1539. importOnlyMeshes: false,
  1540. dummyNodes: []
  1541. };
  1542. // Parse
  1543. if (parsedData.extensions) {
  1544. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1545. }
  1546. if (parsedData.extensionsUsed) {
  1547. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1548. }
  1549. if (parsedData.buffers) {
  1550. parseBuffers(parsedData.buffers, gltfRuntime);
  1551. }
  1552. if (parsedData.bufferViews) {
  1553. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1554. }
  1555. if (parsedData.accessors) {
  1556. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1557. }
  1558. if (parsedData.meshes) {
  1559. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1560. }
  1561. if (parsedData.lights) {
  1562. parseObject(parsedData.lights, "lights", gltfRuntime);
  1563. }
  1564. if (parsedData.cameras) {
  1565. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1566. }
  1567. if (parsedData.nodes) {
  1568. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1569. }
  1570. if (parsedData.images) {
  1571. parseObject(parsedData.images, "images", gltfRuntime);
  1572. }
  1573. if (parsedData.textures) {
  1574. parseObject(parsedData.textures, "textures", gltfRuntime);
  1575. }
  1576. if (parsedData.shaders) {
  1577. parseShaders(parsedData.shaders, gltfRuntime);
  1578. }
  1579. if (parsedData.programs) {
  1580. parseObject(parsedData.programs, "programs", gltfRuntime);
  1581. }
  1582. if (parsedData.samplers) {
  1583. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1584. }
  1585. if (parsedData.techniques) {
  1586. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1587. }
  1588. if (parsedData.materials) {
  1589. parseObject(parsedData.materials, "materials", gltfRuntime);
  1590. }
  1591. if (parsedData.animations) {
  1592. parseObject(parsedData.animations, "animations", gltfRuntime);
  1593. }
  1594. if (parsedData.skins) {
  1595. parseObject(parsedData.skins, "skins", gltfRuntime);
  1596. }
  1597. if (parsedData.scenes) {
  1598. gltfRuntime.scenes = parsedData.scenes;
  1599. }
  1600. if (parsedData.scene && parsedData.scenes) {
  1601. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1602. }
  1603. return gltfRuntime;
  1604. };
  1605. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1606. var buffer = gltfRuntime.buffers[id];
  1607. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  1608. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  1609. }
  1610. else {
  1611. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  1612. if (request) {
  1613. onError(request.status + " " + request.statusText);
  1614. }
  1615. });
  1616. }
  1617. };
  1618. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1619. var texture = gltfRuntime.textures[id];
  1620. if (!texture || !texture.source) {
  1621. onError("");
  1622. return;
  1623. }
  1624. if (texture.babylonTexture) {
  1625. onSuccess(null);
  1626. return;
  1627. }
  1628. var source = gltfRuntime.images[texture.source];
  1629. if (BABYLON.Tools.IsBase64(source.uri)) {
  1630. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  1631. }
  1632. else {
  1633. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  1634. if (request) {
  1635. onError(request.status + " " + request.statusText);
  1636. }
  1637. });
  1638. }
  1639. };
  1640. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1641. var texture = gltfRuntime.textures[id];
  1642. if (texture.babylonTexture) {
  1643. onSuccess(texture.babylonTexture);
  1644. return;
  1645. }
  1646. var sampler = gltfRuntime.samplers[texture.sampler];
  1647. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1648. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1649. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1650. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1651. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1652. var blob = new Blob([buffer]);
  1653. var blobURL = URL.createObjectURL(blob);
  1654. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1655. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1656. if (sampler.wrapS !== undefined) {
  1657. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  1658. }
  1659. if (sampler.wrapT !== undefined) {
  1660. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  1661. }
  1662. newTexture.name = id;
  1663. texture.babylonTexture = newTexture;
  1664. onSuccess(newTexture);
  1665. };
  1666. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1667. var shader = gltfRuntime.shaders[id];
  1668. if (BABYLON.Tools.IsBase64(shader.uri)) {
  1669. var shaderString = atob(shader.uri.split(",")[1]);
  1670. onSuccess(shaderString);
  1671. }
  1672. else {
  1673. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  1674. if (request) {
  1675. onError(request.status + " " + request.statusText);
  1676. }
  1677. });
  1678. }
  1679. };
  1680. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1681. var material = gltfRuntime.materials[id];
  1682. if (!material.technique) {
  1683. if (onError) {
  1684. onError("No technique found.");
  1685. }
  1686. return;
  1687. }
  1688. var technique = gltfRuntime.techniques[material.technique];
  1689. if (!technique) {
  1690. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  1691. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  1692. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1693. onSuccess(defaultMaterial);
  1694. return;
  1695. }
  1696. var program = gltfRuntime.programs[technique.program];
  1697. var states = technique.states;
  1698. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1699. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1700. var newVertexShader = "";
  1701. var newPixelShader = "";
  1702. var vertexTokenizer = new Tokenizer(vertexShader);
  1703. var pixelTokenizer = new Tokenizer(pixelShader);
  1704. var unTreatedUniforms = {};
  1705. var uniforms = [];
  1706. var attributes = [];
  1707. var samplers = [];
  1708. // Fill uniform, sampler2D and attributes
  1709. for (var unif in technique.uniforms) {
  1710. var uniform = technique.uniforms[unif];
  1711. var uniformParameter = technique.parameters[uniform];
  1712. unTreatedUniforms[unif] = uniformParameter;
  1713. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1714. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1715. if (transformIndex !== -1) {
  1716. uniforms.push(babylonTransforms[transformIndex]);
  1717. delete unTreatedUniforms[unif];
  1718. }
  1719. else {
  1720. uniforms.push(unif);
  1721. }
  1722. }
  1723. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  1724. samplers.push(unif);
  1725. }
  1726. else {
  1727. uniforms.push(unif);
  1728. }
  1729. }
  1730. for (var attr in technique.attributes) {
  1731. var attribute = technique.attributes[attr];
  1732. var attributeParameter = technique.parameters[attribute];
  1733. if (attributeParameter.semantic) {
  1734. attributes.push(getAttribute(attributeParameter));
  1735. }
  1736. }
  1737. // Configure vertex shader
  1738. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1739. var tokenType = vertexTokenizer.currentToken;
  1740. if (tokenType !== ETokenType.IDENTIFIER) {
  1741. newVertexShader += vertexTokenizer.currentString;
  1742. continue;
  1743. }
  1744. var foundAttribute = false;
  1745. for (var attr in technique.attributes) {
  1746. var attribute = technique.attributes[attr];
  1747. var attributeParameter = technique.parameters[attribute];
  1748. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1749. newVertexShader += getAttribute(attributeParameter);
  1750. foundAttribute = true;
  1751. break;
  1752. }
  1753. }
  1754. if (foundAttribute) {
  1755. continue;
  1756. }
  1757. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1758. }
  1759. // Configure pixel shader
  1760. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1761. var tokenType = pixelTokenizer.currentToken;
  1762. if (tokenType !== ETokenType.IDENTIFIER) {
  1763. newPixelShader += pixelTokenizer.currentString;
  1764. continue;
  1765. }
  1766. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1767. }
  1768. // Create shader material
  1769. var shaderPath = {
  1770. vertex: program.vertexShader + id,
  1771. fragment: program.fragmentShader + id
  1772. };
  1773. var options = {
  1774. attributes: attributes,
  1775. uniforms: uniforms,
  1776. samplers: samplers,
  1777. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1778. };
  1779. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1780. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1781. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1782. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1783. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1784. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1785. if (states && states.functions) {
  1786. var functions = states.functions;
  1787. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  1788. shaderMaterial.backFaceCulling = false;
  1789. }
  1790. var blendFunc = functions.blendFuncSeparate;
  1791. if (blendFunc) {
  1792. 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) {
  1793. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1794. }
  1795. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1796. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  1797. }
  1798. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1799. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  1800. }
  1801. 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) {
  1802. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  1803. }
  1804. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1805. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  1806. }
  1807. 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) {
  1808. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  1809. }
  1810. }
  1811. }
  1812. };
  1813. return GLTFLoaderBase;
  1814. }());
  1815. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  1816. /**
  1817. * glTF V1 Loader
  1818. */
  1819. var GLTFLoader = /** @class */ (function () {
  1820. function GLTFLoader() {
  1821. // #region Stubs for IGLTFLoader interface
  1822. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  1823. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  1824. this.compileMaterials = false;
  1825. this.useClipPlane = false;
  1826. this.compileShadowGenerators = false;
  1827. this.onDisposeObservable = new BABYLON.Observable();
  1828. this.onMeshLoadedObservable = new BABYLON.Observable();
  1829. this.onTextureLoadedObservable = new BABYLON.Observable();
  1830. this.onMaterialLoadedObservable = new BABYLON.Observable();
  1831. this.onCompleteObservable = new BABYLON.Observable();
  1832. this.onExtensionLoadedObservable = new BABYLON.Observable();
  1833. this.state = null;
  1834. }
  1835. GLTFLoader.RegisterExtension = function (extension) {
  1836. if (GLTFLoader.Extensions[extension.name]) {
  1837. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1838. return;
  1839. }
  1840. GLTFLoader.Extensions[extension.name] = extension;
  1841. };
  1842. GLTFLoader.prototype.dispose = function () { };
  1843. // #endregion
  1844. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  1845. var _this = this;
  1846. scene.useRightHandedSystem = true;
  1847. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1848. gltfRuntime.importOnlyMeshes = true;
  1849. if (meshesNames === "") {
  1850. gltfRuntime.importMeshesNames = [];
  1851. }
  1852. else if (typeof meshesNames === "string") {
  1853. gltfRuntime.importMeshesNames = [meshesNames];
  1854. }
  1855. else if (meshesNames && !(meshesNames instanceof Array)) {
  1856. gltfRuntime.importMeshesNames = [meshesNames];
  1857. }
  1858. else {
  1859. gltfRuntime.importMeshesNames = [];
  1860. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1861. }
  1862. // Create nodes
  1863. _this._createNodes(gltfRuntime);
  1864. var meshes = new Array();
  1865. var skeletons = new Array();
  1866. // Fill arrays of meshes and skeletons
  1867. for (var nde in gltfRuntime.nodes) {
  1868. var node = gltfRuntime.nodes[nde];
  1869. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1870. meshes.push(node.babylonNode);
  1871. }
  1872. }
  1873. for (var skl in gltfRuntime.skins) {
  1874. var skin = gltfRuntime.skins[skl];
  1875. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1876. skeletons.push(skin.babylonSkeleton);
  1877. }
  1878. }
  1879. // Load buffers, shaders, materials, etc.
  1880. _this._loadBuffersAsync(gltfRuntime, function () {
  1881. _this._loadShadersAsync(gltfRuntime, function () {
  1882. importMaterials(gltfRuntime);
  1883. postLoad(gltfRuntime);
  1884. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1885. onSuccess(meshes, [], skeletons);
  1886. }
  1887. });
  1888. }, onProgress);
  1889. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1890. onSuccess(meshes, [], skeletons);
  1891. }
  1892. }, onError);
  1893. return true;
  1894. };
  1895. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  1896. var _this = this;
  1897. return new Promise(function (resolve, reject) {
  1898. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  1899. resolve({
  1900. meshes: meshes,
  1901. particleSystems: particleSystems,
  1902. skeletons: skeletons
  1903. });
  1904. }, onProgress, function (message) {
  1905. reject(new Error(message));
  1906. });
  1907. });
  1908. };
  1909. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  1910. var _this = this;
  1911. scene.useRightHandedSystem = true;
  1912. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1913. // Load runtime extensios
  1914. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  1915. // Create nodes
  1916. _this._createNodes(gltfRuntime);
  1917. // Load buffers, shaders, materials, etc.
  1918. _this._loadBuffersAsync(gltfRuntime, function () {
  1919. _this._loadShadersAsync(gltfRuntime, function () {
  1920. importMaterials(gltfRuntime);
  1921. postLoad(gltfRuntime);
  1922. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  1923. onSuccess();
  1924. }
  1925. });
  1926. });
  1927. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  1928. onSuccess();
  1929. }
  1930. }, onError);
  1931. }, onError);
  1932. };
  1933. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  1934. var _this = this;
  1935. return new Promise(function (resolve, reject) {
  1936. _this._loadAsync(scene, data, rootUrl, function () {
  1937. resolve();
  1938. }, onProgress, function (message) {
  1939. reject(new Error(message));
  1940. });
  1941. });
  1942. };
  1943. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1944. var hasShaders = false;
  1945. var processShader = function (sha, shader) {
  1946. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1947. gltfRuntime.loadedShaderCount++;
  1948. if (shaderString) {
  1949. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1950. }
  1951. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1952. onload();
  1953. }
  1954. }, function () {
  1955. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1956. });
  1957. };
  1958. for (var sha in gltfRuntime.shaders) {
  1959. hasShaders = true;
  1960. var shader = gltfRuntime.shaders[sha];
  1961. if (shader) {
  1962. processShader.bind(this, sha, shader)();
  1963. }
  1964. else {
  1965. BABYLON.Tools.Error("No shader named: " + sha);
  1966. }
  1967. }
  1968. if (!hasShaders) {
  1969. onload();
  1970. }
  1971. };
  1972. ;
  1973. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  1974. var hasBuffers = false;
  1975. var processBuffer = function (buf, buffer) {
  1976. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  1977. gltfRuntime.loadedBufferCount++;
  1978. if (bufferView) {
  1979. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  1980. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  1981. }
  1982. gltfRuntime.loadedBufferViews[buf] = bufferView;
  1983. }
  1984. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  1985. onLoad();
  1986. }
  1987. }, function () {
  1988. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  1989. });
  1990. };
  1991. for (var buf in gltfRuntime.buffers) {
  1992. hasBuffers = true;
  1993. var buffer = gltfRuntime.buffers[buf];
  1994. if (buffer) {
  1995. processBuffer.bind(this, buf, buffer)();
  1996. }
  1997. else {
  1998. BABYLON.Tools.Error("No buffer named: " + buf);
  1999. }
  2000. }
  2001. if (!hasBuffers) {
  2002. onLoad();
  2003. }
  2004. };
  2005. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  2006. var currentScene = gltfRuntime.currentScene;
  2007. if (currentScene) {
  2008. // Only one scene even if multiple scenes are defined
  2009. for (var i = 0; i < currentScene.nodes.length; i++) {
  2010. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2011. }
  2012. }
  2013. else {
  2014. // Load all scenes
  2015. for (var thing in gltfRuntime.scenes) {
  2016. currentScene = gltfRuntime.scenes[thing];
  2017. for (var i = 0; i < currentScene.nodes.length; i++) {
  2018. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2019. }
  2020. }
  2021. }
  2022. };
  2023. GLTFLoader.Extensions = {};
  2024. return GLTFLoader;
  2025. }());
  2026. GLTF1.GLTFLoader = GLTFLoader;
  2027. ;
  2028. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  2029. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2030. })(BABYLON || (BABYLON = {}));
  2031. //# sourceMappingURL=babylon.glTFLoader.js.map
  2032. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2033. var BABYLON;
  2034. (function (BABYLON) {
  2035. var GLTF1;
  2036. (function (GLTF1) {
  2037. /**
  2038. * Utils functions for GLTF
  2039. */
  2040. var GLTFUtils = /** @class */ (function () {
  2041. function GLTFUtils() {
  2042. }
  2043. /**
  2044. * Sets the given "parameter" matrix
  2045. * @param scene: the {BABYLON.Scene} object
  2046. * @param source: the source node where to pick the matrix
  2047. * @param parameter: the GLTF technique parameter
  2048. * @param uniformName: the name of the shader's uniform
  2049. * @param shaderMaterial: the shader material
  2050. */
  2051. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  2052. var mat = null;
  2053. if (parameter.semantic === "MODEL") {
  2054. mat = source.getWorldMatrix();
  2055. }
  2056. else if (parameter.semantic === "PROJECTION") {
  2057. mat = scene.getProjectionMatrix();
  2058. }
  2059. else if (parameter.semantic === "VIEW") {
  2060. mat = scene.getViewMatrix();
  2061. }
  2062. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  2063. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  2064. }
  2065. else if (parameter.semantic === "MODELVIEW") {
  2066. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  2067. }
  2068. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  2069. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  2070. }
  2071. else if (parameter.semantic === "MODELINVERSE") {
  2072. mat = source.getWorldMatrix().invert();
  2073. }
  2074. else if (parameter.semantic === "VIEWINVERSE") {
  2075. mat = scene.getViewMatrix().invert();
  2076. }
  2077. else if (parameter.semantic === "PROJECTIONINVERSE") {
  2078. mat = scene.getProjectionMatrix().invert();
  2079. }
  2080. else if (parameter.semantic === "MODELVIEWINVERSE") {
  2081. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  2082. }
  2083. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  2084. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  2085. }
  2086. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  2087. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  2088. }
  2089. else {
  2090. debugger;
  2091. }
  2092. if (mat) {
  2093. switch (parameter.type) {
  2094. case GLTF1.EParameterType.FLOAT_MAT2:
  2095. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  2096. break;
  2097. case GLTF1.EParameterType.FLOAT_MAT3:
  2098. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  2099. break;
  2100. case GLTF1.EParameterType.FLOAT_MAT4:
  2101. shaderMaterial.setMatrix(uniformName, mat);
  2102. break;
  2103. default: break;
  2104. }
  2105. }
  2106. };
  2107. /**
  2108. * Sets the given "parameter" matrix
  2109. * @param shaderMaterial: the shader material
  2110. * @param uniform: the name of the shader's uniform
  2111. * @param value: the value of the uniform
  2112. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  2113. */
  2114. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  2115. switch (type) {
  2116. case GLTF1.EParameterType.FLOAT:
  2117. shaderMaterial.setFloat(uniform, value);
  2118. return true;
  2119. case GLTF1.EParameterType.FLOAT_VEC2:
  2120. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  2121. return true;
  2122. case GLTF1.EParameterType.FLOAT_VEC3:
  2123. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  2124. return true;
  2125. case GLTF1.EParameterType.FLOAT_VEC4:
  2126. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  2127. return true;
  2128. default: return false;
  2129. }
  2130. };
  2131. /**
  2132. * Returns the wrap mode of the texture
  2133. * @param mode: the mode value
  2134. */
  2135. GLTFUtils.GetWrapMode = function (mode) {
  2136. switch (mode) {
  2137. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  2138. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  2139. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2140. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2141. }
  2142. };
  2143. /**
  2144. * Returns the byte stride giving an accessor
  2145. * @param accessor: the GLTF accessor objet
  2146. */
  2147. GLTFUtils.GetByteStrideFromType = function (accessor) {
  2148. // Needs this function since "byteStride" isn't requiered in glTF format
  2149. var type = accessor.type;
  2150. switch (type) {
  2151. case "VEC2": return 2;
  2152. case "VEC3": return 3;
  2153. case "VEC4": return 4;
  2154. case "MAT2": return 4;
  2155. case "MAT3": return 9;
  2156. case "MAT4": return 16;
  2157. default: return 1;
  2158. }
  2159. };
  2160. /**
  2161. * Returns the texture filter mode giving a mode value
  2162. * @param mode: the filter mode value
  2163. */
  2164. GLTFUtils.GetTextureFilterMode = function (mode) {
  2165. switch (mode) {
  2166. case GLTF1.ETextureFilterType.LINEAR:
  2167. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  2168. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  2169. case GLTF1.ETextureFilterType.NEAREST:
  2170. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  2171. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  2172. }
  2173. };
  2174. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  2175. var byteOffset = bufferView.byteOffset + byteOffset;
  2176. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  2177. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  2178. throw new Error("Buffer access is out of range");
  2179. }
  2180. var buffer = loadedBufferView.buffer;
  2181. byteOffset += loadedBufferView.byteOffset;
  2182. switch (componentType) {
  2183. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  2184. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  2185. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  2186. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  2187. default: return new Float32Array(buffer, byteOffset, byteLength);
  2188. }
  2189. };
  2190. /**
  2191. * Returns a buffer from its accessor
  2192. * @param gltfRuntime: the GLTF runtime
  2193. * @param accessor: the GLTF accessor
  2194. */
  2195. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  2196. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  2197. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  2198. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  2199. };
  2200. /**
  2201. * Decodes a buffer view into a string
  2202. * @param view: the buffer view
  2203. */
  2204. GLTFUtils.DecodeBufferToText = function (view) {
  2205. var result = "";
  2206. var length = view.byteLength;
  2207. for (var i = 0; i < length; ++i) {
  2208. result += String.fromCharCode(view[i]);
  2209. }
  2210. return result;
  2211. };
  2212. /**
  2213. * Returns the default material of gltf. Related to
  2214. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  2215. * @param scene: the Babylon.js scene
  2216. */
  2217. GLTFUtils.GetDefaultMaterial = function (scene) {
  2218. if (!GLTFUtils._DefaultMaterial) {
  2219. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  2220. "precision highp float;",
  2221. "",
  2222. "uniform mat4 worldView;",
  2223. "uniform mat4 projection;",
  2224. "",
  2225. "attribute vec3 position;",
  2226. "",
  2227. "void main(void)",
  2228. "{",
  2229. " gl_Position = projection * worldView * vec4(position, 1.0);",
  2230. "}"
  2231. ].join("\n");
  2232. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  2233. "precision highp float;",
  2234. "",
  2235. "uniform vec4 u_emission;",
  2236. "",
  2237. "void main(void)",
  2238. "{",
  2239. " gl_FragColor = u_emission;",
  2240. "}"
  2241. ].join("\n");
  2242. var shaderPath = {
  2243. vertex: "GLTFDefaultMaterial",
  2244. fragment: "GLTFDefaultMaterial"
  2245. };
  2246. var options = {
  2247. attributes: ["position"],
  2248. uniforms: ["worldView", "projection", "u_emission"],
  2249. samplers: new Array(),
  2250. needAlphaBlending: false
  2251. };
  2252. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  2253. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  2254. }
  2255. return GLTFUtils._DefaultMaterial;
  2256. };
  2257. // The GLTF default material
  2258. GLTFUtils._DefaultMaterial = null;
  2259. return GLTFUtils;
  2260. }());
  2261. GLTF1.GLTFUtils = GLTFUtils;
  2262. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2263. })(BABYLON || (BABYLON = {}));
  2264. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  2265. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2266. var BABYLON;
  2267. (function (BABYLON) {
  2268. var GLTF1;
  2269. (function (GLTF1) {
  2270. var GLTFLoaderExtension = /** @class */ (function () {
  2271. function GLTFLoaderExtension(name) {
  2272. this._name = name;
  2273. }
  2274. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  2275. get: function () {
  2276. return this._name;
  2277. },
  2278. enumerable: true,
  2279. configurable: true
  2280. });
  2281. /**
  2282. * Defines an override for loading the runtime
  2283. * Return true to stop further extensions from loading the runtime
  2284. */
  2285. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2286. return false;
  2287. };
  2288. /**
  2289. * Defines an onverride for creating gltf runtime
  2290. * Return true to stop further extensions from creating the runtime
  2291. */
  2292. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2293. return false;
  2294. };
  2295. /**
  2296. * Defines an override for loading buffers
  2297. * Return true to stop further extensions from loading this buffer
  2298. */
  2299. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2300. return false;
  2301. };
  2302. /**
  2303. * Defines an override for loading texture buffers
  2304. * Return true to stop further extensions from loading this texture data
  2305. */
  2306. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2307. return false;
  2308. };
  2309. /**
  2310. * Defines an override for creating textures
  2311. * Return true to stop further extensions from loading this texture
  2312. */
  2313. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2314. return false;
  2315. };
  2316. /**
  2317. * Defines an override for loading shader strings
  2318. * Return true to stop further extensions from loading this shader data
  2319. */
  2320. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2321. return false;
  2322. };
  2323. /**
  2324. * Defines an override for loading materials
  2325. * Return true to stop further extensions from loading this material
  2326. */
  2327. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2328. return false;
  2329. };
  2330. // ---------
  2331. // Utilities
  2332. // ---------
  2333. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2334. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2335. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  2336. }, function () {
  2337. setTimeout(function () {
  2338. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2339. });
  2340. });
  2341. };
  2342. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2343. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2344. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  2345. }, function () {
  2346. setTimeout(function () {
  2347. onSuccess();
  2348. });
  2349. });
  2350. };
  2351. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2352. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2353. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2354. }, function () {
  2355. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2356. });
  2357. };
  2358. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  2359. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  2360. };
  2361. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2362. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2363. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2364. }, function () {
  2365. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2366. });
  2367. };
  2368. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2369. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2370. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2371. }, function () {
  2372. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2373. });
  2374. };
  2375. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2376. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2377. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2378. }, function () {
  2379. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2380. });
  2381. };
  2382. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2383. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2384. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2385. }, function () {
  2386. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2387. });
  2388. };
  2389. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  2390. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  2391. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  2392. if (func(loaderExtension)) {
  2393. return;
  2394. }
  2395. }
  2396. defaultFunc();
  2397. };
  2398. return GLTFLoaderExtension;
  2399. }());
  2400. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  2401. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2402. })(BABYLON || (BABYLON = {}));
  2403. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2404. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2405. var __extends = (this && this.__extends) || (function () {
  2406. var extendStatics = Object.setPrototypeOf ||
  2407. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2408. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2409. return function (d, b) {
  2410. extendStatics(d, b);
  2411. function __() { this.constructor = d; }
  2412. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2413. };
  2414. })();
  2415. var BABYLON;
  2416. (function (BABYLON) {
  2417. var GLTF1;
  2418. (function (GLTF1) {
  2419. var BinaryExtensionBufferName = "binary_glTF";
  2420. ;
  2421. ;
  2422. var GLTFBinaryExtension = /** @class */ (function (_super) {
  2423. __extends(GLTFBinaryExtension, _super);
  2424. function GLTFBinaryExtension() {
  2425. return _super.call(this, "KHR_binary_glTF") || this;
  2426. }
  2427. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2428. var extensionsUsed = data.json.extensionsUsed;
  2429. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  2430. return false;
  2431. }
  2432. this._bin = data.bin;
  2433. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2434. return true;
  2435. };
  2436. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2437. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  2438. return false;
  2439. }
  2440. if (id !== BinaryExtensionBufferName) {
  2441. return false;
  2442. }
  2443. onSuccess(this._bin);
  2444. return true;
  2445. };
  2446. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2447. var texture = gltfRuntime.textures[id];
  2448. var source = gltfRuntime.images[texture.source];
  2449. if (!source.extensions || !(this.name in source.extensions)) {
  2450. return false;
  2451. }
  2452. var sourceExt = source.extensions[this.name];
  2453. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  2454. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2455. onSuccess(buffer);
  2456. return true;
  2457. };
  2458. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2459. var shader = gltfRuntime.shaders[id];
  2460. if (!shader.extensions || !(this.name in shader.extensions)) {
  2461. return false;
  2462. }
  2463. var binaryExtensionShader = shader.extensions[this.name];
  2464. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  2465. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2466. setTimeout(function () {
  2467. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  2468. onSuccess(shaderString);
  2469. });
  2470. return true;
  2471. };
  2472. return GLTFBinaryExtension;
  2473. }(GLTF1.GLTFLoaderExtension));
  2474. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  2475. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  2476. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2477. })(BABYLON || (BABYLON = {}));
  2478. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  2479. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2480. var __extends = (this && this.__extends) || (function () {
  2481. var extendStatics = Object.setPrototypeOf ||
  2482. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2483. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2484. return function (d, b) {
  2485. extendStatics(d, b);
  2486. function __() { this.constructor = d; }
  2487. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2488. };
  2489. })();
  2490. var BABYLON;
  2491. (function (BABYLON) {
  2492. var GLTF1;
  2493. (function (GLTF1) {
  2494. ;
  2495. ;
  2496. ;
  2497. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  2498. __extends(GLTFMaterialsCommonExtension, _super);
  2499. function GLTFMaterialsCommonExtension() {
  2500. return _super.call(this, "KHR_materials_common") || this;
  2501. }
  2502. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2503. if (!gltfRuntime.extensions)
  2504. return false;
  2505. var extension = gltfRuntime.extensions[this.name];
  2506. if (!extension)
  2507. return false;
  2508. // Create lights
  2509. var lights = extension.lights;
  2510. if (lights) {
  2511. for (var thing in lights) {
  2512. var light = lights[thing];
  2513. switch (light.type) {
  2514. case "ambient":
  2515. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  2516. var ambient = light.ambient;
  2517. if (ambient) {
  2518. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  2519. }
  2520. break;
  2521. case "point":
  2522. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  2523. var point = light.point;
  2524. if (point) {
  2525. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  2526. }
  2527. break;
  2528. case "directional":
  2529. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  2530. var directional = light.directional;
  2531. if (directional) {
  2532. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  2533. }
  2534. break;
  2535. case "spot":
  2536. var spot = light.spot;
  2537. if (spot) {
  2538. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  2539. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  2540. }
  2541. break;
  2542. default:
  2543. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  2544. break;
  2545. }
  2546. }
  2547. }
  2548. return false;
  2549. };
  2550. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2551. var material = gltfRuntime.materials[id];
  2552. if (!material || !material.extensions)
  2553. return false;
  2554. var extension = material.extensions[this.name];
  2555. if (!extension)
  2556. return false;
  2557. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2558. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2559. if (extension.technique === "CONSTANT") {
  2560. standardMaterial.disableLighting = true;
  2561. }
  2562. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  2563. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  2564. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  2565. // Ambient
  2566. if (typeof extension.values.ambient === "string") {
  2567. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  2568. }
  2569. else {
  2570. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  2571. }
  2572. // Diffuse
  2573. if (typeof extension.values.diffuse === "string") {
  2574. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  2575. }
  2576. else {
  2577. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  2578. }
  2579. // Emission
  2580. if (typeof extension.values.emission === "string") {
  2581. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  2582. }
  2583. else {
  2584. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  2585. }
  2586. // Specular
  2587. if (typeof extension.values.specular === "string") {
  2588. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  2589. }
  2590. else {
  2591. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  2592. }
  2593. return true;
  2594. };
  2595. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  2596. // Create buffer from texture url
  2597. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2598. // Create texture from buffer
  2599. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  2600. }, onError);
  2601. };
  2602. return GLTFMaterialsCommonExtension;
  2603. }(GLTF1.GLTFLoaderExtension));
  2604. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  2605. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  2606. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2607. })(BABYLON || (BABYLON = {}));
  2608. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map