babylon.glTF2Serializer.js 215 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563
  1. BABYLON.Effect.ShadersStore['textureTransformPixelShader'] = "precision highp float;\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 textureTransformMat;\nvoid main(void) {\nvec2 uvTransformed=(textureTransformMat*vec4(vUV.xy,1,1)).xy;\ngl_FragColor=texture2D(textureSampler,uvTransformed);\n}";
  2. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  3. var BABYLON;
  4. (function (BABYLON) {
  5. ;
  6. /**
  7. * Class for generating glTF data from a Babylon scene.
  8. */
  9. var GLTF2Export = /** @class */ (function () {
  10. function GLTF2Export() {
  11. }
  12. /**
  13. * Exports the geometry of the scene to .gltf file format asynchronously
  14. * @param scene Babylon scene with scene hierarchy information
  15. * @param filePrefix File prefix to use when generating the glTF file
  16. * @param options Exporter options
  17. * @returns Returns an object with a .gltf file and associates texture names
  18. * as keys and their data and paths as values
  19. */
  20. GLTF2Export.GLTFAsync = function (scene, filePrefix, options) {
  21. return scene.whenReadyAsync().then(function () {
  22. var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
  23. var gltfGenerator = new BABYLON.GLTF2.Exporter._Exporter(scene, options);
  24. return gltfGenerator._generateGLTFAsync(glTFPrefix);
  25. });
  26. };
  27. GLTF2Export._PreExportAsync = function (scene, options) {
  28. return Promise.resolve().then(function () {
  29. if (options && options.exportWithoutWaitingForScene) {
  30. return Promise.resolve();
  31. }
  32. else {
  33. return scene.whenReadyAsync();
  34. }
  35. });
  36. };
  37. GLTF2Export._PostExportAsync = function (scene, glTFData, options) {
  38. return Promise.resolve().then(function () {
  39. if (options && options.exportWithoutWaitingForScene) {
  40. return glTFData;
  41. }
  42. else {
  43. return glTFData;
  44. }
  45. });
  46. };
  47. /**
  48. * Exports the geometry of the scene to .glb file format asychronously
  49. * @param scene Babylon scene with scene hierarchy information
  50. * @param filePrefix File prefix to use when generating glb file
  51. * @param options Exporter options
  52. * @returns Returns an object with a .glb filename as key and data as value
  53. */
  54. GLTF2Export.GLBAsync = function (scene, filePrefix, options) {
  55. var _this = this;
  56. return this._PreExportAsync(scene, options).then(function () {
  57. var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
  58. var gltfGenerator = new BABYLON.GLTF2.Exporter._Exporter(scene, options);
  59. return gltfGenerator._generateGLBAsync(glTFPrefix).then(function (glTFData) {
  60. return _this._PostExportAsync(scene, glTFData, options);
  61. });
  62. });
  63. };
  64. return GLTF2Export;
  65. }());
  66. BABYLON.GLTF2Export = GLTF2Export;
  67. })(BABYLON || (BABYLON = {}));
  68. //# sourceMappingURL=babylon.glTFSerializer.js.map
  69. /// <reference path="../../../../dist/preview release/glTF2Interface/babylon.glTF2Interface.d.ts"/>
  70. var BABYLON;
  71. (function (BABYLON) {
  72. var GLTF2;
  73. (function (GLTF2) {
  74. var Exporter;
  75. (function (Exporter) {
  76. /**
  77. * Utility interface for storing vertex attribute data
  78. * @hidden
  79. */
  80. /**
  81. * Converts Babylon Scene into glTF 2.0.
  82. * @hidden
  83. */
  84. var _Exporter = /** @class */ (function () {
  85. /**
  86. * Creates a glTF Exporter instance, which can accept optional exporter options
  87. * @param babylonScene Babylon scene object
  88. * @param options Options to modify the behavior of the exporter
  89. */
  90. function _Exporter(babylonScene, options) {
  91. this._extensions = {};
  92. this._asset = { generator: "BabylonJS", version: "2.0" };
  93. this._extensionsUsed = [];
  94. this._extensionsRequired = [];
  95. this._babylonScene = babylonScene;
  96. this._bufferViews = [];
  97. this._accessors = [];
  98. this._meshes = [];
  99. this._scenes = [];
  100. this._nodes = [];
  101. this._images = [];
  102. this._materials = [];
  103. this._materialMap = [];
  104. this._textures = [];
  105. this._samplers = [];
  106. this._animations = [];
  107. this._imageData = {};
  108. this._convertToRightHandedSystem = this._babylonScene.useRightHandedSystem ? false : true;
  109. var _options = options || {};
  110. this._shouldExportTransformNode = _options.shouldExportTransformNode ? _options.shouldExportTransformNode : function (babylonTransformNode) { return true; };
  111. this._animationSampleRate = _options.animationSampleRate ? _options.animationSampleRate : 1 / 60;
  112. this._glTFMaterialExporter = new Exporter._GLTFMaterialExporter(this);
  113. this._loadExtensions();
  114. }
  115. _Exporter.prototype._applyExtensions = function (property, actionAsync) {
  116. for (var _i = 0, _a = _Exporter._ExtensionNames; _i < _a.length; _i++) {
  117. var name_1 = _a[_i];
  118. var extension = this._extensions[name_1];
  119. if (extension.enabled) {
  120. var exporterProperty = property;
  121. exporterProperty._activeLoaderExtensions = exporterProperty._activeLoaderExtensions || {};
  122. var activeLoaderExtensions = exporterProperty._activeLoaderExtensions;
  123. if (!activeLoaderExtensions[name_1]) {
  124. activeLoaderExtensions[name_1] = true;
  125. try {
  126. var result = actionAsync(extension);
  127. if (result) {
  128. return result;
  129. }
  130. }
  131. finally {
  132. delete activeLoaderExtensions[name_1];
  133. delete exporterProperty._activeLoaderExtensions;
  134. }
  135. }
  136. }
  137. }
  138. return null;
  139. };
  140. _Exporter.prototype._extensionsPreExportTextureAsync = function (context, babylonTexture, mimeType) {
  141. return this._applyExtensions(babylonTexture, function (extension) { return extension.preExportTextureAsync && extension.preExportTextureAsync(context, babylonTexture, mimeType); });
  142. };
  143. _Exporter.prototype._extensionsPostExportMeshPrimitiveAsync = function (context, meshPrimitive, babylonSubMesh, binaryWriter) {
  144. return this._applyExtensions(meshPrimitive, function (extension) { return extension.postExportMeshPrimitiveAsync && extension.postExportMeshPrimitiveAsync(context, meshPrimitive, babylonSubMesh, binaryWriter); });
  145. };
  146. /**
  147. * Load glTF serializer extensions
  148. */
  149. _Exporter.prototype._loadExtensions = function () {
  150. for (var _i = 0, _a = _Exporter._ExtensionNames; _i < _a.length; _i++) {
  151. var name_2 = _a[_i];
  152. var extension = _Exporter._ExtensionFactories[name_2](this);
  153. this._extensions[name_2] = extension;
  154. }
  155. };
  156. /**
  157. * Registers a glTF exporter extension
  158. * @param name Name of the extension to export
  159. * @param factory The factory function that creates the exporter extension
  160. */
  161. _Exporter.RegisterExtension = function (name, factory) {
  162. if (_Exporter.UnregisterExtension(name)) {
  163. BABYLON.Tools.Warn("Extension with the name " + name + " already exists");
  164. }
  165. _Exporter._ExtensionFactories[name] = factory;
  166. _Exporter._ExtensionNames.push(name);
  167. };
  168. /**
  169. * Un-registers an exporter extension
  170. * @param name The name fo the exporter extension
  171. * @returns A boolean indicating whether the extension has been un-registered
  172. */
  173. _Exporter.UnregisterExtension = function (name) {
  174. if (!_Exporter._ExtensionFactories[name]) {
  175. return false;
  176. }
  177. delete _Exporter._ExtensionFactories[name];
  178. var index = _Exporter._ExtensionNames.indexOf(name);
  179. if (index !== -1) {
  180. _Exporter._ExtensionNames.splice(index, 1);
  181. }
  182. return true;
  183. };
  184. /**
  185. * Lazy load a local engine with premultiplied alpha set to false
  186. */
  187. _Exporter.prototype._getLocalEngine = function () {
  188. if (!this._localEngine) {
  189. var localCanvas = document.createElement('canvas');
  190. localCanvas.id = "WriteCanvas";
  191. localCanvas.width = 2048;
  192. localCanvas.height = 2048;
  193. this._localEngine = new BABYLON.Engine(localCanvas, true, { premultipliedAlpha: false, preserveDrawingBuffer: true });
  194. this._localEngine.setViewport(new BABYLON.Viewport(0, 0, 1, 1));
  195. }
  196. return this._localEngine;
  197. };
  198. _Exporter.prototype.reorderIndicesBasedOnPrimitiveMode = function (submesh, primitiveMode, babylonIndices, byteOffset, binaryWriter) {
  199. switch (primitiveMode) {
  200. case BABYLON.Material.TriangleFillMode: {
  201. if (!byteOffset) {
  202. byteOffset = 0;
  203. }
  204. for (var i = submesh.indexStart, length_1 = submesh.indexStart + submesh.indexCount; i < length_1; i = i + 3) {
  205. var index = byteOffset + i * 4;
  206. // swap the second and third indices
  207. var secondIndex = binaryWriter.getUInt32(index + 4);
  208. var thirdIndex = binaryWriter.getUInt32(index + 8);
  209. binaryWriter.setUInt32(thirdIndex, index + 4);
  210. binaryWriter.setUInt32(secondIndex, index + 8);
  211. }
  212. break;
  213. }
  214. case BABYLON.Material.TriangleFanDrawMode: {
  215. for (var i = submesh.indexStart + submesh.indexCount - 1, start = submesh.indexStart; i >= start; --i) {
  216. binaryWriter.setUInt32(babylonIndices[i], byteOffset);
  217. byteOffset += 4;
  218. }
  219. break;
  220. }
  221. case BABYLON.Material.TriangleStripDrawMode: {
  222. if (submesh.indexCount >= 3) {
  223. binaryWriter.setUInt32(babylonIndices[submesh.indexStart + 2], byteOffset + 4);
  224. binaryWriter.setUInt32(babylonIndices[submesh.indexStart + 1], byteOffset + 8);
  225. }
  226. break;
  227. }
  228. }
  229. };
  230. /**
  231. * Reorders the vertex attribute data based on the primitive mode. This is necessary when indices are not available and the winding order is
  232. * clock-wise during export to glTF
  233. * @param submesh BabylonJS submesh
  234. * @param primitiveMode Primitive mode of the mesh
  235. * @param sideOrientation the winding order of the submesh
  236. * @param vertexBufferKind The type of vertex attribute
  237. * @param meshAttributeArray The vertex attribute data
  238. * @param byteOffset The offset to the binary data
  239. * @param binaryWriter The binary data for the glTF file
  240. */
  241. _Exporter.prototype.reorderVertexAttributeDataBasedOnPrimitiveMode = function (submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter) {
  242. if (this._convertToRightHandedSystem && sideOrientation === BABYLON.Material.ClockWiseSideOrientation) {
  243. switch (primitiveMode) {
  244. case BABYLON.Material.TriangleFillMode: {
  245. this.reorderTriangleFillMode(submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter);
  246. break;
  247. }
  248. case BABYLON.Material.TriangleStripDrawMode: {
  249. this.reorderTriangleStripDrawMode(submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter);
  250. break;
  251. }
  252. case BABYLON.Material.TriangleFanDrawMode: {
  253. this.reorderTriangleFanMode(submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter);
  254. break;
  255. }
  256. }
  257. }
  258. };
  259. /**
  260. * Reorders the vertex attributes in the correct triangle mode order . This is necessary when indices are not available and the winding order is
  261. * clock-wise during export to glTF
  262. * @param submesh BabylonJS submesh
  263. * @param primitiveMode Primitive mode of the mesh
  264. * @param sideOrientation the winding order of the submesh
  265. * @param vertexBufferKind The type of vertex attribute
  266. * @param meshAttributeArray The vertex attribute data
  267. * @param byteOffset The offset to the binary data
  268. * @param binaryWriter The binary data for the glTF file
  269. */
  270. _Exporter.prototype.reorderTriangleFillMode = function (submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter) {
  271. var vertexBuffer = this.getVertexBufferFromMesh(vertexBufferKind, submesh.getMesh());
  272. if (vertexBuffer) {
  273. var stride = vertexBuffer.byteStride / BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  274. if (submesh.verticesCount % 3 !== 0) {
  275. BABYLON.Tools.Error('The submesh vertices for the triangle fill mode is not divisible by 3!');
  276. }
  277. else {
  278. var vertexData = [];
  279. var index = 0;
  280. switch (vertexBufferKind) {
  281. case BABYLON.VertexBuffer.PositionKind:
  282. case BABYLON.VertexBuffer.NormalKind: {
  283. for (var x = submesh.verticesStart; x < submesh.verticesStart + submesh.verticesCount; x = x + 3) {
  284. index = x * stride;
  285. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index));
  286. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + 2 * stride));
  287. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + stride));
  288. }
  289. break;
  290. }
  291. case BABYLON.VertexBuffer.TangentKind: {
  292. for (var x = submesh.verticesStart; x < submesh.verticesStart + submesh.verticesCount; x = x + 3) {
  293. index = x * stride;
  294. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index));
  295. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index + 2 * stride));
  296. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index + stride));
  297. }
  298. break;
  299. }
  300. case BABYLON.VertexBuffer.ColorKind: {
  301. var size = vertexBuffer.getSize();
  302. for (var x = submesh.verticesStart; x < submesh.verticesStart + submesh.verticesCount; x = x + size) {
  303. index = x * stride;
  304. if (size === 4) {
  305. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index));
  306. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index + 2 * stride));
  307. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index + stride));
  308. }
  309. else {
  310. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index));
  311. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + 2 * stride));
  312. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + stride));
  313. }
  314. }
  315. break;
  316. }
  317. case BABYLON.VertexBuffer.UVKind:
  318. case BABYLON.VertexBuffer.UV2Kind: {
  319. for (var x = submesh.verticesStart; x < submesh.verticesStart + submesh.verticesCount; x = x + 3) {
  320. index = x * stride;
  321. vertexData.push(BABYLON.Vector2.FromArray(meshAttributeArray, index));
  322. vertexData.push(BABYLON.Vector2.FromArray(meshAttributeArray, index + 2 * stride));
  323. vertexData.push(BABYLON.Vector2.FromArray(meshAttributeArray, index + stride));
  324. }
  325. break;
  326. }
  327. default: {
  328. BABYLON.Tools.Error("Unsupported Vertex Buffer type: " + vertexBufferKind);
  329. }
  330. }
  331. this.writeVertexAttributeData(vertexData, byteOffset, vertexBufferKind, meshAttributeArray, binaryWriter);
  332. }
  333. }
  334. else {
  335. BABYLON.Tools.Warn("reorderTriangleFillMode: Vertex Buffer Kind " + vertexBufferKind + " not present!");
  336. }
  337. };
  338. /**
  339. * Reorders the vertex attributes in the correct triangle strip order. This is necessary when indices are not available and the winding order is
  340. * clock-wise during export to glTF
  341. * @param submesh BabylonJS submesh
  342. * @param primitiveMode Primitive mode of the mesh
  343. * @param sideOrientation the winding order of the submesh
  344. * @param vertexBufferKind The type of vertex attribute
  345. * @param meshAttributeArray The vertex attribute data
  346. * @param byteOffset The offset to the binary data
  347. * @param binaryWriter The binary data for the glTF file
  348. */
  349. _Exporter.prototype.reorderTriangleStripDrawMode = function (submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter) {
  350. var vertexBuffer = this.getVertexBufferFromMesh(vertexBufferKind, submesh.getMesh());
  351. if (vertexBuffer) {
  352. var stride = vertexBuffer.byteStride / BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  353. var vertexData = [];
  354. var index = 0;
  355. switch (vertexBufferKind) {
  356. case BABYLON.VertexBuffer.PositionKind:
  357. case BABYLON.VertexBuffer.NormalKind: {
  358. index = submesh.verticesStart;
  359. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + 2 * stride));
  360. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + stride));
  361. break;
  362. }
  363. case BABYLON.VertexBuffer.TangentKind: {
  364. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  365. index = x * stride;
  366. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index));
  367. }
  368. break;
  369. }
  370. case BABYLON.VertexBuffer.ColorKind: {
  371. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  372. index = x * stride;
  373. vertexBuffer.getSize() === 4 ? vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index)) : vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index));
  374. }
  375. break;
  376. }
  377. case BABYLON.VertexBuffer.UVKind:
  378. case BABYLON.VertexBuffer.UV2Kind: {
  379. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  380. index = x * stride;
  381. vertexData.push(BABYLON.Vector2.FromArray(meshAttributeArray, index));
  382. }
  383. break;
  384. }
  385. default: {
  386. BABYLON.Tools.Error("Unsupported Vertex Buffer type: " + vertexBufferKind);
  387. }
  388. }
  389. this.writeVertexAttributeData(vertexData, byteOffset + 12, vertexBufferKind, meshAttributeArray, binaryWriter);
  390. }
  391. else {
  392. BABYLON.Tools.Warn("reorderTriangleStripDrawMode: Vertex buffer kind " + vertexBufferKind + " not present!");
  393. }
  394. };
  395. /**
  396. * Reorders the vertex attributes in the correct triangle fan order. This is necessary when indices are not available and the winding order is
  397. * clock-wise during export to glTF
  398. * @param submesh BabylonJS submesh
  399. * @param primitiveMode Primitive mode of the mesh
  400. * @param sideOrientation the winding order of the submesh
  401. * @param vertexBufferKind The type of vertex attribute
  402. * @param meshAttributeArray The vertex attribute data
  403. * @param byteOffset The offset to the binary data
  404. * @param binaryWriter The binary data for the glTF file
  405. */
  406. _Exporter.prototype.reorderTriangleFanMode = function (submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter) {
  407. var vertexBuffer = this.getVertexBufferFromMesh(vertexBufferKind, submesh.getMesh());
  408. if (vertexBuffer) {
  409. var stride = vertexBuffer.byteStride / BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  410. var vertexData = [];
  411. var index = 0;
  412. switch (vertexBufferKind) {
  413. case BABYLON.VertexBuffer.PositionKind:
  414. case BABYLON.VertexBuffer.NormalKind: {
  415. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  416. index = x * stride;
  417. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index));
  418. }
  419. break;
  420. }
  421. case BABYLON.VertexBuffer.TangentKind: {
  422. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  423. index = x * stride;
  424. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index));
  425. }
  426. break;
  427. }
  428. case BABYLON.VertexBuffer.ColorKind: {
  429. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  430. index = x * stride;
  431. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index));
  432. vertexBuffer.getSize() === 4 ? vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index)) : vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index));
  433. }
  434. break;
  435. }
  436. case BABYLON.VertexBuffer.UVKind:
  437. case BABYLON.VertexBuffer.UV2Kind: {
  438. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  439. index = x * stride;
  440. vertexData.push(BABYLON.Vector2.FromArray(meshAttributeArray, index));
  441. }
  442. break;
  443. }
  444. default: {
  445. BABYLON.Tools.Error("Unsupported Vertex Buffer type: " + vertexBufferKind);
  446. }
  447. }
  448. this.writeVertexAttributeData(vertexData, byteOffset, vertexBufferKind, meshAttributeArray, binaryWriter);
  449. }
  450. else {
  451. BABYLON.Tools.Warn("reorderTriangleFanMode: Vertex buffer kind " + vertexBufferKind + " not present!");
  452. }
  453. };
  454. /**
  455. * Writes the vertex attribute data to binary
  456. * @param vertices The vertices to write to the binary writer
  457. * @param byteOffset The offset into the binary writer to overwrite binary data
  458. * @param vertexAttributeKind The vertex attribute type
  459. * @param meshAttributeArray The vertex attribute data
  460. * @param binaryWriter The writer containing the binary data
  461. */
  462. _Exporter.prototype.writeVertexAttributeData = function (vertices, byteOffset, vertexAttributeKind, meshAttributeArray, binaryWriter) {
  463. for (var _i = 0, vertices_1 = vertices; _i < vertices_1.length; _i++) {
  464. var vertex = vertices_1[_i];
  465. if (this._convertToRightHandedSystem && !(vertexAttributeKind === BABYLON.VertexBuffer.ColorKind) && !(vertex instanceof BABYLON.Vector2)) {
  466. if (vertex instanceof BABYLON.Vector3) {
  467. if (vertexAttributeKind === BABYLON.VertexBuffer.NormalKind) {
  468. Exporter._GLTFUtilities._GetRightHandedNormalVector3FromRef(vertex);
  469. }
  470. else if (vertexAttributeKind === BABYLON.VertexBuffer.PositionKind) {
  471. Exporter._GLTFUtilities._GetRightHandedPositionVector3FromRef(vertex);
  472. }
  473. else {
  474. BABYLON.Tools.Error('Unsupported vertex attribute kind!');
  475. }
  476. }
  477. else {
  478. Exporter._GLTFUtilities._GetRightHandedVector4FromRef(vertex);
  479. }
  480. }
  481. if (vertexAttributeKind === BABYLON.VertexBuffer.NormalKind) {
  482. vertex.normalize();
  483. }
  484. else if (vertexAttributeKind === BABYLON.VertexBuffer.TangentKind && vertex instanceof BABYLON.Vector4) {
  485. Exporter._GLTFUtilities._NormalizeTangentFromRef(vertex);
  486. }
  487. for (var _a = 0, _b = vertex.asArray(); _a < _b.length; _a++) {
  488. var component = _b[_a];
  489. binaryWriter.setFloat32(component, byteOffset);
  490. byteOffset += 4;
  491. }
  492. }
  493. };
  494. /**
  495. * Writes mesh attribute data to a data buffer
  496. * Returns the bytelength of the data
  497. * @param vertexBufferKind Indicates what kind of vertex data is being passed in
  498. * @param meshAttributeArray Array containing the attribute data
  499. * @param binaryWriter The buffer to write the binary data to
  500. * @param indices Used to specify the order of the vertex data
  501. */
  502. _Exporter.prototype.writeAttributeData = function (vertexBufferKind, meshAttributeArray, byteStride, binaryWriter) {
  503. var stride = byteStride / 4;
  504. var vertexAttributes = [];
  505. var index;
  506. switch (vertexBufferKind) {
  507. case BABYLON.VertexBuffer.PositionKind: {
  508. for (var k = 0, length_2 = meshAttributeArray.length / stride; k < length_2; ++k) {
  509. index = k * stride;
  510. var vertexData = BABYLON.Vector3.FromArray(meshAttributeArray, index);
  511. if (this._convertToRightHandedSystem) {
  512. Exporter._GLTFUtilities._GetRightHandedPositionVector3FromRef(vertexData);
  513. }
  514. vertexAttributes.push(vertexData.asArray());
  515. }
  516. break;
  517. }
  518. case BABYLON.VertexBuffer.NormalKind: {
  519. for (var k = 0, length_3 = meshAttributeArray.length / stride; k < length_3; ++k) {
  520. index = k * stride;
  521. var vertexData = BABYLON.Vector3.FromArray(meshAttributeArray, index);
  522. if (this._convertToRightHandedSystem) {
  523. Exporter._GLTFUtilities._GetRightHandedNormalVector3FromRef(vertexData);
  524. }
  525. vertexData.normalize();
  526. vertexAttributes.push(vertexData.asArray());
  527. }
  528. break;
  529. }
  530. case BABYLON.VertexBuffer.TangentKind: {
  531. for (var k = 0, length_4 = meshAttributeArray.length / stride; k < length_4; ++k) {
  532. index = k * stride;
  533. var vertexData = BABYLON.Vector4.FromArray(meshAttributeArray, index);
  534. if (this._convertToRightHandedSystem) {
  535. Exporter._GLTFUtilities._GetRightHandedVector4FromRef(vertexData);
  536. }
  537. Exporter._GLTFUtilities._NormalizeTangentFromRef(vertexData);
  538. vertexAttributes.push(vertexData.asArray());
  539. }
  540. break;
  541. }
  542. case BABYLON.VertexBuffer.ColorKind: {
  543. for (var k = 0, length_5 = meshAttributeArray.length / stride; k < length_5; ++k) {
  544. index = k * stride;
  545. var vertexData = stride === 3 ? BABYLON.Vector3.FromArray(meshAttributeArray, index) : BABYLON.Vector4.FromArray(meshAttributeArray, index);
  546. vertexAttributes.push(vertexData.asArray());
  547. }
  548. break;
  549. }
  550. case BABYLON.VertexBuffer.UVKind:
  551. case BABYLON.VertexBuffer.UV2Kind: {
  552. for (var k = 0, length_6 = meshAttributeArray.length / stride; k < length_6; ++k) {
  553. index = k * stride;
  554. vertexAttributes.push(this._convertToRightHandedSystem ? [meshAttributeArray[index], meshAttributeArray[index + 1]] : [meshAttributeArray[index], meshAttributeArray[index + 1]]);
  555. }
  556. break;
  557. }
  558. default: {
  559. BABYLON.Tools.Warn("Unsupported Vertex Buffer Type: " + vertexBufferKind);
  560. vertexAttributes = [];
  561. }
  562. }
  563. for (var _i = 0, vertexAttributes_1 = vertexAttributes; _i < vertexAttributes_1.length; _i++) {
  564. var vertexAttribute = vertexAttributes_1[_i];
  565. for (var _a = 0, vertexAttribute_1 = vertexAttribute; _a < vertexAttribute_1.length; _a++) {
  566. var component = vertexAttribute_1[_a];
  567. binaryWriter.setFloat32(component);
  568. }
  569. }
  570. };
  571. /**
  572. * Generates glTF json data
  573. * @param shouldUseGlb Indicates whether the json should be written for a glb file
  574. * @param glTFPrefix Text to use when prefixing a glTF file
  575. * @param prettyPrint Indicates whether the json file should be pretty printed (true) or not (false)
  576. * @returns json data as string
  577. */
  578. _Exporter.prototype.generateJSON = function (shouldUseGlb, glTFPrefix, prettyPrint) {
  579. var _this = this;
  580. var buffer = { byteLength: this._totalByteLength };
  581. var imageName;
  582. var imageData;
  583. var bufferView;
  584. var byteOffset = this._totalByteLength;
  585. var glTF = {
  586. asset: this._asset
  587. };
  588. if (this._extensionsUsed && this._extensionsUsed.length) {
  589. glTF.extensionsUsed = this._extensionsUsed;
  590. }
  591. if (this._extensionsRequired && this._extensionsRequired.length) {
  592. glTF.extensionsRequired = this._extensionsRequired;
  593. }
  594. if (buffer.byteLength) {
  595. glTF.buffers = [buffer];
  596. }
  597. if (this._nodes && this._nodes.length) {
  598. glTF.nodes = this._nodes;
  599. }
  600. if (this._meshes && this._meshes.length) {
  601. glTF.meshes = this._meshes;
  602. }
  603. if (this._scenes && this._scenes.length) {
  604. glTF.scenes = this._scenes;
  605. glTF.scene = 0;
  606. }
  607. if (this._bufferViews && this._bufferViews.length) {
  608. glTF.bufferViews = this._bufferViews;
  609. }
  610. if (this._accessors && this._accessors.length) {
  611. glTF.accessors = this._accessors;
  612. }
  613. if (this._animations && this._animations.length) {
  614. glTF.animations = this._animations;
  615. }
  616. if (this._materials && this._materials.length) {
  617. glTF.materials = this._materials;
  618. }
  619. if (this._textures && this._textures.length) {
  620. glTF.textures = this._textures;
  621. }
  622. if (this._samplers && this._samplers.length) {
  623. glTF.samplers = this._samplers;
  624. }
  625. if (this._images && this._images.length) {
  626. if (!shouldUseGlb) {
  627. glTF.images = this._images;
  628. }
  629. else {
  630. glTF.images = [];
  631. this._images.forEach(function (image) {
  632. if (image.uri) {
  633. imageData = _this._imageData[image.uri];
  634. imageName = image.uri.split('.')[0] + " image";
  635. bufferView = Exporter._GLTFUtilities._CreateBufferView(0, byteOffset, imageData.data.length, undefined, imageName);
  636. byteOffset += imageData.data.buffer.byteLength;
  637. _this._bufferViews.push(bufferView);
  638. image.bufferView = _this._bufferViews.length - 1;
  639. image.name = imageName;
  640. image.mimeType = imageData.mimeType;
  641. image.uri = undefined;
  642. if (!glTF.images) {
  643. glTF.images = [];
  644. }
  645. glTF.images.push(image);
  646. }
  647. });
  648. // Replace uri with bufferview and mime type for glb
  649. buffer.byteLength = byteOffset;
  650. }
  651. }
  652. if (!shouldUseGlb) {
  653. buffer.uri = glTFPrefix + ".bin";
  654. }
  655. var jsonText = prettyPrint ? JSON.stringify(glTF, null, 2) : JSON.stringify(glTF);
  656. return jsonText;
  657. };
  658. /**
  659. * Generates data for .gltf and .bin files based on the glTF prefix string
  660. * @param glTFPrefix Text to use when prefixing a glTF file
  661. * @returns GLTFData with glTF file data
  662. */
  663. _Exporter.prototype._generateGLTFAsync = function (glTFPrefix) {
  664. var _this = this;
  665. return this._generateBinaryAsync().then(function (binaryBuffer) {
  666. var jsonText = _this.generateJSON(false, glTFPrefix, true);
  667. var bin = new Blob([binaryBuffer], { type: 'application/octet-stream' });
  668. var glTFFileName = glTFPrefix + '.gltf';
  669. var glTFBinFile = glTFPrefix + '.bin';
  670. var container = new BABYLON.GLTFData();
  671. container.glTFFiles[glTFFileName] = jsonText;
  672. container.glTFFiles[glTFBinFile] = bin;
  673. if (_this._imageData) {
  674. for (var image in _this._imageData) {
  675. container.glTFFiles[image] = new Blob([_this._imageData[image].data], { type: _this._imageData[image].mimeType });
  676. }
  677. }
  678. return container;
  679. });
  680. };
  681. /**
  682. * Creates a binary buffer for glTF
  683. * @returns array buffer for binary data
  684. */
  685. _Exporter.prototype._generateBinaryAsync = function () {
  686. var _this = this;
  687. var binaryWriter = new _BinaryWriter(4);
  688. return this.createSceneAsync(this._babylonScene, binaryWriter).then(function () {
  689. if (_this._localEngine) {
  690. _this._localEngine.dispose();
  691. }
  692. return binaryWriter.getArrayBuffer();
  693. });
  694. };
  695. /**
  696. * Pads the number to a multiple of 4
  697. * @param num number to pad
  698. * @returns padded number
  699. */
  700. _Exporter.prototype._getPadding = function (num) {
  701. var remainder = num % 4;
  702. var padding = remainder === 0 ? remainder : 4 - remainder;
  703. return padding;
  704. };
  705. /**
  706. * Generates a glb file from the json and binary data
  707. * Returns an object with the glb file name as the key and data as the value
  708. * @param glTFPrefix
  709. * @returns object with glb filename as key and data as value
  710. */
  711. _Exporter.prototype._generateGLBAsync = function (glTFPrefix) {
  712. var _this = this;
  713. return this._generateBinaryAsync().then(function (binaryBuffer) {
  714. var jsonText = _this.generateJSON(true);
  715. var glbFileName = glTFPrefix + '.glb';
  716. var headerLength = 12;
  717. var chunkLengthPrefix = 8;
  718. var jsonLength = jsonText.length;
  719. var imageByteLength = 0;
  720. for (var key in _this._imageData) {
  721. imageByteLength += _this._imageData[key].data.byteLength;
  722. }
  723. var jsonPadding = _this._getPadding(jsonLength);
  724. var binPadding = _this._getPadding(binaryBuffer.byteLength);
  725. var imagePadding = _this._getPadding(imageByteLength);
  726. var byteLength = headerLength + (2 * chunkLengthPrefix) + jsonLength + jsonPadding + binaryBuffer.byteLength + binPadding + imageByteLength + imagePadding;
  727. //header
  728. var headerBuffer = new ArrayBuffer(headerLength);
  729. var headerBufferView = new DataView(headerBuffer);
  730. headerBufferView.setUint32(0, 0x46546C67, true); //glTF
  731. headerBufferView.setUint32(4, 2, true); // version
  732. headerBufferView.setUint32(8, byteLength, true); // total bytes in file
  733. //json chunk
  734. var jsonChunkBuffer = new ArrayBuffer(chunkLengthPrefix + jsonLength + jsonPadding);
  735. var jsonChunkBufferView = new DataView(jsonChunkBuffer);
  736. jsonChunkBufferView.setUint32(0, jsonLength + jsonPadding, true);
  737. jsonChunkBufferView.setUint32(4, 0x4E4F534A, true);
  738. //json chunk bytes
  739. var jsonData = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix);
  740. for (var i = 0; i < jsonLength; ++i) {
  741. jsonData[i] = jsonText.charCodeAt(i);
  742. }
  743. //json padding
  744. var jsonPaddingView = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix + jsonLength);
  745. for (var i = 0; i < jsonPadding; ++i) {
  746. jsonPaddingView[i] = 0x20;
  747. }
  748. //binary chunk
  749. var binaryChunkBuffer = new ArrayBuffer(chunkLengthPrefix);
  750. var binaryChunkBufferView = new DataView(binaryChunkBuffer);
  751. binaryChunkBufferView.setUint32(0, binaryBuffer.byteLength + imageByteLength + imagePadding, true);
  752. binaryChunkBufferView.setUint32(4, 0x004E4942, true);
  753. // binary padding
  754. var binPaddingBuffer = new ArrayBuffer(binPadding);
  755. var binPaddingView = new Uint8Array(binPaddingBuffer);
  756. for (var i = 0; i < binPadding; ++i) {
  757. binPaddingView[i] = 0;
  758. }
  759. var imagePaddingBuffer = new ArrayBuffer(imagePadding);
  760. var imagePaddingView = new Uint8Array(imagePaddingBuffer);
  761. for (var i = 0; i < imagePadding; ++i) {
  762. imagePaddingView[i] = 0;
  763. }
  764. var glbData = [headerBuffer, jsonChunkBuffer, binaryChunkBuffer, binaryBuffer];
  765. // binary data
  766. for (var key in _this._imageData) {
  767. glbData.push(_this._imageData[key].data.buffer);
  768. }
  769. glbData.push(binPaddingBuffer);
  770. glbData.push(imagePaddingBuffer);
  771. var glbFile = new Blob(glbData, { type: 'application/octet-stream' });
  772. var container = new BABYLON.GLTFData();
  773. container.glTFFiles[glbFileName] = glbFile;
  774. if (_this._localEngine != null) {
  775. _this._localEngine.dispose();
  776. }
  777. return container;
  778. });
  779. };
  780. /**
  781. * Sets the TRS for each node
  782. * @param node glTF Node for storing the transformation data
  783. * @param babylonTransformNode Babylon mesh used as the source for the transformation data
  784. */
  785. _Exporter.prototype.setNodeTransformation = function (node, babylonTransformNode) {
  786. if (!babylonTransformNode.getPivotPoint().equalsToFloats(0, 0, 0)) {
  787. BABYLON.Tools.Warn("Pivot points are not supported in the glTF serializer");
  788. }
  789. if (!babylonTransformNode.position.equalsToFloats(0, 0, 0)) {
  790. node.translation = this._convertToRightHandedSystem ? Exporter._GLTFUtilities._GetRightHandedPositionVector3(babylonTransformNode.position).asArray() : babylonTransformNode.position.asArray();
  791. }
  792. if (!babylonTransformNode.scaling.equalsToFloats(1, 1, 1)) {
  793. node.scale = babylonTransformNode.scaling.asArray();
  794. }
  795. var rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(babylonTransformNode.rotation.y, babylonTransformNode.rotation.x, babylonTransformNode.rotation.z);
  796. if (babylonTransformNode.rotationQuaternion) {
  797. rotationQuaternion.multiplyInPlace(babylonTransformNode.rotationQuaternion);
  798. }
  799. if (!(rotationQuaternion.x === 0 && rotationQuaternion.y === 0 && rotationQuaternion.z === 0 && rotationQuaternion.w === 1)) {
  800. if (this._convertToRightHandedSystem) {
  801. Exporter._GLTFUtilities._GetRightHandedQuaternionFromRef(rotationQuaternion);
  802. }
  803. node.rotation = rotationQuaternion.normalize().asArray();
  804. }
  805. };
  806. _Exporter.prototype.getVertexBufferFromMesh = function (attributeKind, bufferMesh) {
  807. if (bufferMesh.isVerticesDataPresent(attributeKind)) {
  808. var vertexBuffer = bufferMesh.getVertexBuffer(attributeKind);
  809. if (vertexBuffer) {
  810. return vertexBuffer;
  811. }
  812. }
  813. return null;
  814. };
  815. /**
  816. * Creates a bufferview based on the vertices type for the Babylon mesh
  817. * @param kind Indicates the type of vertices data
  818. * @param babylonTransformNode The Babylon mesh to get the vertices data from
  819. * @param binaryWriter The buffer to write the bufferview data to
  820. */
  821. _Exporter.prototype.createBufferViewKind = function (kind, babylonTransformNode, binaryWriter, byteStride) {
  822. var bufferMesh = babylonTransformNode instanceof BABYLON.Mesh ?
  823. babylonTransformNode : babylonTransformNode instanceof BABYLON.InstancedMesh ?
  824. babylonTransformNode.sourceMesh : null;
  825. if (bufferMesh) {
  826. var vertexData = bufferMesh.getVerticesData(kind);
  827. if (vertexData) {
  828. var byteLength = vertexData.length * 4;
  829. var bufferView = Exporter._GLTFUtilities._CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, byteStride, kind + " - " + bufferMesh.name);
  830. this._bufferViews.push(bufferView);
  831. this.writeAttributeData(kind, vertexData, byteStride, binaryWriter);
  832. }
  833. }
  834. };
  835. /**
  836. * The primitive mode of the Babylon mesh
  837. * @param babylonMesh The BabylonJS mesh
  838. */
  839. _Exporter.prototype.getMeshPrimitiveMode = function (babylonMesh) {
  840. if (babylonMesh instanceof BABYLON.LinesMesh) {
  841. return BABYLON.Material.LineListDrawMode;
  842. }
  843. return babylonMesh.material ? babylonMesh.material.fillMode : BABYLON.Material.TriangleFillMode;
  844. };
  845. /**
  846. * Sets the primitive mode of the glTF mesh primitive
  847. * @param meshPrimitive glTF mesh primitive
  848. * @param primitiveMode The primitive mode
  849. */
  850. _Exporter.prototype.setPrimitiveMode = function (meshPrimitive, primitiveMode) {
  851. switch (primitiveMode) {
  852. case BABYLON.Material.TriangleFillMode: {
  853. // glTF defaults to using Triangle Mode
  854. break;
  855. }
  856. case BABYLON.Material.TriangleStripDrawMode: {
  857. meshPrimitive.mode = 5 /* TRIANGLE_STRIP */;
  858. break;
  859. }
  860. case BABYLON.Material.TriangleFanDrawMode: {
  861. meshPrimitive.mode = 6 /* TRIANGLE_FAN */;
  862. break;
  863. }
  864. case BABYLON.Material.PointListDrawMode: {
  865. meshPrimitive.mode = 0 /* POINTS */;
  866. }
  867. case BABYLON.Material.PointFillMode: {
  868. meshPrimitive.mode = 0 /* POINTS */;
  869. break;
  870. }
  871. case BABYLON.Material.LineLoopDrawMode: {
  872. meshPrimitive.mode = 2 /* LINE_LOOP */;
  873. break;
  874. }
  875. case BABYLON.Material.LineListDrawMode: {
  876. meshPrimitive.mode = 1 /* LINES */;
  877. break;
  878. }
  879. case BABYLON.Material.LineStripDrawMode: {
  880. meshPrimitive.mode = 3 /* LINE_STRIP */;
  881. break;
  882. }
  883. }
  884. };
  885. /**
  886. * Sets the vertex attribute accessor based of the glTF mesh primitive
  887. * @param meshPrimitive glTF mesh primitive
  888. * @param attributeKind vertex attribute
  889. * @returns boolean specifying if uv coordinates are present
  890. */
  891. _Exporter.prototype.setAttributeKind = function (meshPrimitive, attributeKind) {
  892. switch (attributeKind) {
  893. case BABYLON.VertexBuffer.PositionKind: {
  894. meshPrimitive.attributes.POSITION = this._accessors.length - 1;
  895. break;
  896. }
  897. case BABYLON.VertexBuffer.NormalKind: {
  898. meshPrimitive.attributes.NORMAL = this._accessors.length - 1;
  899. break;
  900. }
  901. case BABYLON.VertexBuffer.ColorKind: {
  902. meshPrimitive.attributes.COLOR_0 = this._accessors.length - 1;
  903. break;
  904. }
  905. case BABYLON.VertexBuffer.TangentKind: {
  906. meshPrimitive.attributes.TANGENT = this._accessors.length - 1;
  907. break;
  908. }
  909. case BABYLON.VertexBuffer.UVKind: {
  910. meshPrimitive.attributes.TEXCOORD_0 = this._accessors.length - 1;
  911. break;
  912. }
  913. case BABYLON.VertexBuffer.UV2Kind: {
  914. meshPrimitive.attributes.TEXCOORD_1 = this._accessors.length - 1;
  915. break;
  916. }
  917. default: {
  918. BABYLON.Tools.Warn("Unsupported Vertex Buffer Type: " + attributeKind);
  919. }
  920. }
  921. };
  922. /**
  923. * Sets data for the primitive attributes of each submesh
  924. * @param mesh glTF Mesh object to store the primitive attribute information
  925. * @param babylonTransformNode Babylon mesh to get the primitive attribute data from
  926. * @param binaryWriter Buffer to write the attribute data to
  927. */
  928. _Exporter.prototype.setPrimitiveAttributesAsync = function (mesh, babylonTransformNode, binaryWriter) {
  929. var promises = [];
  930. var bufferMesh = null;
  931. var bufferView;
  932. var uvCoordsPresent;
  933. var minMax;
  934. if (babylonTransformNode instanceof BABYLON.Mesh) {
  935. bufferMesh = babylonTransformNode;
  936. }
  937. else if (babylonTransformNode instanceof BABYLON.InstancedMesh) {
  938. bufferMesh = babylonTransformNode.sourceMesh;
  939. }
  940. var attributeData = [
  941. { kind: BABYLON.VertexBuffer.PositionKind, accessorType: "VEC3" /* VEC3 */, byteStride: 12 },
  942. { kind: BABYLON.VertexBuffer.NormalKind, accessorType: "VEC3" /* VEC3 */, byteStride: 12 },
  943. { kind: BABYLON.VertexBuffer.ColorKind, accessorType: "VEC4" /* VEC4 */, byteStride: 16 },
  944. { kind: BABYLON.VertexBuffer.TangentKind, accessorType: "VEC4" /* VEC4 */, byteStride: 16 },
  945. { kind: BABYLON.VertexBuffer.UVKind, accessorType: "VEC2" /* VEC2 */, byteStride: 8 },
  946. { kind: BABYLON.VertexBuffer.UV2Kind, accessorType: "VEC2" /* VEC2 */, byteStride: 8 },
  947. ];
  948. if (bufferMesh) {
  949. var indexBufferViewIndex = null;
  950. var primitiveMode = this.getMeshPrimitiveMode(bufferMesh);
  951. var vertexAttributeBufferViews = {};
  952. // For each BabylonMesh, create bufferviews for each 'kind'
  953. for (var _i = 0, attributeData_1 = attributeData; _i < attributeData_1.length; _i++) {
  954. var attribute = attributeData_1[_i];
  955. var attributeKind = attribute.kind;
  956. if (bufferMesh.isVerticesDataPresent(attributeKind)) {
  957. var vertexBuffer = this.getVertexBufferFromMesh(attributeKind, bufferMesh);
  958. attribute.byteStride = vertexBuffer ? vertexBuffer.getSize() * 4 : BABYLON.VertexBuffer.DeduceStride(attributeKind) * 4;
  959. if (attribute.byteStride === 12) {
  960. attribute.accessorType = "VEC3" /* VEC3 */;
  961. }
  962. this.createBufferViewKind(attributeKind, babylonTransformNode, binaryWriter, attribute.byteStride);
  963. attribute.bufferViewIndex = this._bufferViews.length - 1;
  964. vertexAttributeBufferViews[attributeKind] = attribute.bufferViewIndex;
  965. }
  966. }
  967. if (bufferMesh.getTotalIndices()) {
  968. var indices = bufferMesh.getIndices();
  969. if (indices) {
  970. var byteLength = indices.length * 4;
  971. bufferView = Exporter._GLTFUtilities._CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, undefined, "Indices - " + bufferMesh.name);
  972. this._bufferViews.push(bufferView);
  973. indexBufferViewIndex = this._bufferViews.length - 1;
  974. for (var k = 0, length_7 = indices.length; k < length_7; ++k) {
  975. binaryWriter.setUInt32(indices[k]);
  976. }
  977. }
  978. }
  979. if (bufferMesh.subMeshes) {
  980. // go through all mesh primitives (submeshes)
  981. for (var _a = 0, _b = bufferMesh.subMeshes; _a < _b.length; _a++) {
  982. var submesh = _b[_a];
  983. uvCoordsPresent = false;
  984. var babylonMaterial = submesh.getMaterial() || bufferMesh.getScene().defaultMaterial;
  985. var materialIndex = null;
  986. if (babylonMaterial) {
  987. if (bufferMesh instanceof BABYLON.LinesMesh) {
  988. // get the color from the lines mesh and set it in the material
  989. var material = {
  990. name: bufferMesh.name + ' material'
  991. };
  992. if (!bufferMesh.color.equals(BABYLON.Color3.White()) || bufferMesh.alpha < 1) {
  993. material.pbrMetallicRoughness = {
  994. baseColorFactor: bufferMesh.color.asArray().concat([bufferMesh.alpha])
  995. };
  996. }
  997. this._materials.push(material);
  998. materialIndex = this._materials.length - 1;
  999. }
  1000. else if (babylonMaterial instanceof BABYLON.MultiMaterial) {
  1001. var subMaterial = babylonMaterial.subMaterials[submesh.materialIndex];
  1002. if (subMaterial) {
  1003. babylonMaterial = subMaterial;
  1004. materialIndex = this._materialMap[babylonMaterial.uniqueId];
  1005. }
  1006. }
  1007. else {
  1008. materialIndex = this._materialMap[babylonMaterial.uniqueId];
  1009. }
  1010. }
  1011. var glTFMaterial = materialIndex != null ? this._materials[materialIndex] : null;
  1012. var meshPrimitive = { attributes: {} };
  1013. this.setPrimitiveMode(meshPrimitive, primitiveMode);
  1014. for (var _c = 0, attributeData_2 = attributeData; _c < attributeData_2.length; _c++) {
  1015. var attribute = attributeData_2[_c];
  1016. var attributeKind = attribute.kind;
  1017. if (attributeKind === BABYLON.VertexBuffer.UVKind || attributeKind === BABYLON.VertexBuffer.UV2Kind) {
  1018. if (glTFMaterial && !this._glTFMaterialExporter._hasTexturesPresent(glTFMaterial)) {
  1019. continue;
  1020. }
  1021. }
  1022. var vertexData = bufferMesh.getVerticesData(attributeKind);
  1023. if (vertexData) {
  1024. var vertexBuffer = this.getVertexBufferFromMesh(attributeKind, bufferMesh);
  1025. if (vertexBuffer) {
  1026. var stride = vertexBuffer.getSize();
  1027. var bufferViewIndex = attribute.bufferViewIndex;
  1028. if (bufferViewIndex != undefined) { // check to see if bufferviewindex has a numeric value assigned.
  1029. minMax = { min: null, max: null };
  1030. if (attributeKind == BABYLON.VertexBuffer.PositionKind) {
  1031. minMax = Exporter._GLTFUtilities._CalculateMinMaxPositions(vertexData, 0, vertexData.length / stride, this._convertToRightHandedSystem);
  1032. }
  1033. var accessor = Exporter._GLTFUtilities._CreateAccessor(bufferViewIndex, attributeKind + " - " + babylonTransformNode.name, attribute.accessorType, 5126 /* FLOAT */, vertexData.length / stride, 0, minMax.min, minMax.max);
  1034. this._accessors.push(accessor);
  1035. this.setAttributeKind(meshPrimitive, attributeKind);
  1036. if (meshPrimitive.attributes.TEXCOORD_0 != null || meshPrimitive.attributes.TEXCOORD_1 != null) {
  1037. uvCoordsPresent = true;
  1038. }
  1039. }
  1040. }
  1041. }
  1042. }
  1043. if (indexBufferViewIndex) {
  1044. // Create accessor
  1045. var accessor = Exporter._GLTFUtilities._CreateAccessor(indexBufferViewIndex, "indices - " + babylonTransformNode.name, "SCALAR" /* SCALAR */, 5125 /* UNSIGNED_INT */, submesh.indexCount, submesh.indexStart * 4, null, null);
  1046. this._accessors.push(accessor);
  1047. meshPrimitive.indices = this._accessors.length - 1;
  1048. }
  1049. if (materialIndex != null && Object.keys(meshPrimitive.attributes).length > 0) {
  1050. var sideOrientation = babylonMaterial.sideOrientation;
  1051. if (this._convertToRightHandedSystem && sideOrientation === BABYLON.Material.ClockWiseSideOrientation) {
  1052. //Overwrite the indices to be counter-clockwise
  1053. var byteOffset = indexBufferViewIndex != null ? this._bufferViews[indexBufferViewIndex].byteOffset : null;
  1054. if (byteOffset == null) {
  1055. byteOffset = 0;
  1056. }
  1057. var babylonIndices = null;
  1058. if (indexBufferViewIndex != null) {
  1059. babylonIndices = bufferMesh.getIndices();
  1060. }
  1061. if (babylonIndices) {
  1062. this.reorderIndicesBasedOnPrimitiveMode(submesh, primitiveMode, babylonIndices, byteOffset, binaryWriter);
  1063. }
  1064. else {
  1065. for (var _d = 0, attributeData_3 = attributeData; _d < attributeData_3.length; _d++) {
  1066. var attribute = attributeData_3[_d];
  1067. var vertexData = bufferMesh.getVerticesData(attribute.kind);
  1068. if (vertexData) {
  1069. var byteOffset_1 = this._bufferViews[vertexAttributeBufferViews[attribute.kind]].byteOffset;
  1070. if (!byteOffset_1) {
  1071. byteOffset_1 = 0;
  1072. }
  1073. this.reorderVertexAttributeDataBasedOnPrimitiveMode(submesh, primitiveMode, sideOrientation, attribute.kind, vertexData, byteOffset_1, binaryWriter);
  1074. }
  1075. }
  1076. }
  1077. }
  1078. if (!uvCoordsPresent && this._glTFMaterialExporter._hasTexturesPresent(this._materials[materialIndex])) {
  1079. var newMat = this._glTFMaterialExporter._stripTexturesFromMaterial(this._materials[materialIndex]);
  1080. this._materials.push(newMat);
  1081. materialIndex = this._materials.length - 1;
  1082. }
  1083. meshPrimitive.material = materialIndex;
  1084. }
  1085. mesh.primitives.push(meshPrimitive);
  1086. var promise = this._extensionsPostExportMeshPrimitiveAsync("postExport", meshPrimitive, submesh, binaryWriter);
  1087. if (promise) {
  1088. promises.push();
  1089. }
  1090. }
  1091. }
  1092. }
  1093. return Promise.all(promises).then(function () {
  1094. /* do nothing */
  1095. });
  1096. };
  1097. /**
  1098. * Creates a glTF scene based on the array of meshes
  1099. * Returns the the total byte offset
  1100. * @param babylonScene Babylon scene to get the mesh data from
  1101. * @param binaryWriter Buffer to write binary data to
  1102. */
  1103. _Exporter.prototype.createSceneAsync = function (babylonScene, binaryWriter) {
  1104. var _this = this;
  1105. var scene = { nodes: [] };
  1106. var glTFNodeIndex;
  1107. var glTFNode;
  1108. var directDescendents;
  1109. var nodes = babylonScene.transformNodes.concat(babylonScene.meshes);
  1110. return this._glTFMaterialExporter._convertMaterialsToGLTFAsync(babylonScene.materials, "image/png" /* PNG */, true).then(function () {
  1111. return _this.createNodeMapAndAnimationsAsync(babylonScene, nodes, _this._shouldExportTransformNode, binaryWriter).then(function (nodeMap) {
  1112. _this._nodeMap = nodeMap;
  1113. _this._totalByteLength = binaryWriter.getByteOffset();
  1114. if (_this._totalByteLength == undefined) {
  1115. throw new Error("undefined byte length!");
  1116. }
  1117. // Build Hierarchy with the node map.
  1118. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  1119. var babylonTransformNode = nodes_1[_i];
  1120. glTFNodeIndex = _this._nodeMap[babylonTransformNode.uniqueId];
  1121. if (glTFNodeIndex != null) {
  1122. glTFNode = _this._nodes[glTFNodeIndex];
  1123. if (!babylonTransformNode.parent) {
  1124. if (!_this._shouldExportTransformNode(babylonTransformNode)) {
  1125. BABYLON.Tools.Log("Omitting " + babylonTransformNode.name + " from scene.");
  1126. }
  1127. else {
  1128. if (_this._convertToRightHandedSystem) {
  1129. if (glTFNode.translation) {
  1130. glTFNode.translation[2] *= -1;
  1131. glTFNode.translation[0] *= -1;
  1132. }
  1133. glTFNode.rotation = glTFNode.rotation ? BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(BABYLON.Quaternion.FromArray(glTFNode.rotation)).asArray() : (BABYLON.Quaternion.FromArray([0, 1, 0, 0])).asArray();
  1134. }
  1135. scene.nodes.push(glTFNodeIndex);
  1136. }
  1137. }
  1138. directDescendents = babylonTransformNode.getDescendants(true);
  1139. if (!glTFNode.children && directDescendents && directDescendents.length) {
  1140. var children = [];
  1141. for (var _a = 0, directDescendents_1 = directDescendents; _a < directDescendents_1.length; _a++) {
  1142. var descendent = directDescendents_1[_a];
  1143. if (_this._nodeMap[descendent.uniqueId] != null) {
  1144. children.push(_this._nodeMap[descendent.uniqueId]);
  1145. }
  1146. }
  1147. if (children.length) {
  1148. glTFNode.children = children;
  1149. }
  1150. }
  1151. }
  1152. }
  1153. ;
  1154. if (scene.nodes.length) {
  1155. _this._scenes.push(scene);
  1156. }
  1157. });
  1158. });
  1159. };
  1160. /**
  1161. * Creates a mapping of Node unique id to node index and handles animations
  1162. * @param babylonScene Babylon Scene
  1163. * @param nodes Babylon transform nodes
  1164. * @param shouldExportTransformNode Callback specifying if a transform node should be exported
  1165. * @param binaryWriter Buffer to write binary data to
  1166. * @returns Node mapping of unique id to index
  1167. */
  1168. _Exporter.prototype.createNodeMapAndAnimationsAsync = function (babylonScene, nodes, shouldExportTransformNode, binaryWriter) {
  1169. var _this = this;
  1170. var promiseChain = Promise.resolve();
  1171. var nodeMap = {};
  1172. var nodeIndex;
  1173. var runtimeGLTFAnimation = {
  1174. name: 'runtime animations',
  1175. channels: [],
  1176. samplers: []
  1177. };
  1178. var idleGLTFAnimations = [];
  1179. var _loop_1 = function (babylonTransformNode) {
  1180. if (shouldExportTransformNode(babylonTransformNode)) {
  1181. promiseChain = promiseChain.then(function () {
  1182. return _this.createNodeAsync(babylonTransformNode, binaryWriter).then(function (node) {
  1183. var directDescendents = babylonTransformNode.getDescendants(true, function (node) { return (node instanceof BABYLON.TransformNode); });
  1184. if (directDescendents.length || node.mesh != null) {
  1185. _this._nodes.push(node);
  1186. nodeIndex = _this._nodes.length - 1;
  1187. nodeMap[babylonTransformNode.uniqueId] = nodeIndex;
  1188. }
  1189. if (!babylonScene.animationGroups.length && babylonTransformNode.animations.length) {
  1190. Exporter._GLTFAnimation._CreateNodeAnimationFromTransformNodeAnimations(babylonTransformNode, runtimeGLTFAnimation, idleGLTFAnimations, nodeMap, _this._nodes, binaryWriter, _this._bufferViews, _this._accessors, _this._convertToRightHandedSystem, _this._animationSampleRate);
  1191. }
  1192. });
  1193. });
  1194. }
  1195. else {
  1196. "Excluding mesh " + babylonTransformNode.name;
  1197. }
  1198. };
  1199. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  1200. var babylonTransformNode = nodes_2[_i];
  1201. _loop_1(babylonTransformNode);
  1202. }
  1203. ;
  1204. return promiseChain.then(function () {
  1205. if (runtimeGLTFAnimation.channels.length && runtimeGLTFAnimation.samplers.length) {
  1206. _this._animations.push(runtimeGLTFAnimation);
  1207. }
  1208. idleGLTFAnimations.forEach(function (idleGLTFAnimation) {
  1209. if (idleGLTFAnimation.channels.length && idleGLTFAnimation.samplers.length) {
  1210. _this._animations.push(idleGLTFAnimation);
  1211. }
  1212. });
  1213. if (babylonScene.animationGroups.length) {
  1214. Exporter._GLTFAnimation._CreateNodeAnimationFromAnimationGroups(babylonScene, _this._animations, nodeMap, _this._nodes, binaryWriter, _this._bufferViews, _this._accessors, _this._convertToRightHandedSystem, _this._animationSampleRate);
  1215. }
  1216. return nodeMap;
  1217. });
  1218. };
  1219. /**
  1220. * Creates a glTF node from a Babylon mesh
  1221. * @param babylonMesh Source Babylon mesh
  1222. * @param binaryWriter Buffer for storing geometry data
  1223. * @returns glTF node
  1224. */
  1225. _Exporter.prototype.createNodeAsync = function (babylonTransformNode, binaryWriter) {
  1226. var _this = this;
  1227. return Promise.resolve().then(function () {
  1228. // create node to hold translation/rotation/scale and the mesh
  1229. var node = {};
  1230. // create mesh
  1231. var mesh = { primitives: [] };
  1232. if (babylonTransformNode.name) {
  1233. node.name = babylonTransformNode.name;
  1234. }
  1235. // Set transformation
  1236. _this.setNodeTransformation(node, babylonTransformNode);
  1237. return _this.setPrimitiveAttributesAsync(mesh, babylonTransformNode, binaryWriter).then(function () {
  1238. if (mesh.primitives.length) {
  1239. _this._meshes.push(mesh);
  1240. node.mesh = _this._meshes.length - 1;
  1241. }
  1242. return node;
  1243. });
  1244. });
  1245. };
  1246. _Exporter._ExtensionNames = new Array();
  1247. _Exporter._ExtensionFactories = {};
  1248. return _Exporter;
  1249. }());
  1250. Exporter._Exporter = _Exporter;
  1251. /**
  1252. * @hidden
  1253. *
  1254. * Stores glTF binary data. If the array buffer byte length is exceeded, it doubles in size dynamically
  1255. */
  1256. var _BinaryWriter = /** @class */ (function () {
  1257. /**
  1258. * Initialize binary writer with an initial byte length
  1259. * @param byteLength Initial byte length of the array buffer
  1260. */
  1261. function _BinaryWriter(byteLength) {
  1262. this._arrayBuffer = new ArrayBuffer(byteLength);
  1263. this._dataView = new DataView(this._arrayBuffer);
  1264. this._byteOffset = 0;
  1265. }
  1266. /**
  1267. * Resize the array buffer to the specified byte length
  1268. * @param byteLength
  1269. */
  1270. _BinaryWriter.prototype.resizeBuffer = function (byteLength) {
  1271. var newBuffer = new ArrayBuffer(byteLength);
  1272. var oldUint8Array = new Uint8Array(this._arrayBuffer);
  1273. var newUint8Array = new Uint8Array(newBuffer);
  1274. for (var i = 0, length_8 = newUint8Array.byteLength; i < length_8; ++i) {
  1275. newUint8Array[i] = oldUint8Array[i];
  1276. }
  1277. this._arrayBuffer = newBuffer;
  1278. this._dataView = new DataView(this._arrayBuffer);
  1279. return newBuffer;
  1280. };
  1281. /**
  1282. * Get an array buffer with the length of the byte offset
  1283. * @returns ArrayBuffer resized to the byte offset
  1284. */
  1285. _BinaryWriter.prototype.getArrayBuffer = function () {
  1286. return this.resizeBuffer(this.getByteOffset());
  1287. };
  1288. /**
  1289. * Get the byte offset of the array buffer
  1290. * @returns byte offset
  1291. */
  1292. _BinaryWriter.prototype.getByteOffset = function () {
  1293. if (this._byteOffset == undefined) {
  1294. throw new Error("Byte offset is undefined!");
  1295. }
  1296. return this._byteOffset;
  1297. };
  1298. /**
  1299. * Stores an UInt8 in the array buffer
  1300. * @param entry
  1301. * @param byteOffset If defined, specifies where to set the value as an offset.
  1302. */
  1303. _BinaryWriter.prototype.setUInt8 = function (entry, byteOffset) {
  1304. if (byteOffset != null) {
  1305. if (byteOffset < this._byteOffset) {
  1306. this._dataView.setUint8(byteOffset, entry);
  1307. }
  1308. else {
  1309. BABYLON.Tools.Error('BinaryWriter: byteoffset is greater than the current binary buffer length!');
  1310. }
  1311. }
  1312. else {
  1313. if (this._byteOffset + 1 > this._arrayBuffer.byteLength) {
  1314. this.resizeBuffer(this._arrayBuffer.byteLength * 2);
  1315. }
  1316. this._dataView.setUint8(this._byteOffset++, entry);
  1317. }
  1318. };
  1319. /**
  1320. * Gets an UInt32 in the array buffer
  1321. * @param entry
  1322. * @param byteOffset If defined, specifies where to set the value as an offset.
  1323. */
  1324. _BinaryWriter.prototype.getUInt32 = function (byteOffset) {
  1325. if (byteOffset < this._byteOffset) {
  1326. return this._dataView.getUint32(byteOffset, true);
  1327. }
  1328. else {
  1329. BABYLON.Tools.Error('BinaryWriter: byteoffset is greater than the current binary buffer length!');
  1330. throw new Error('BinaryWriter: byteoffset is greater than the current binary buffer length!');
  1331. }
  1332. };
  1333. _BinaryWriter.prototype.getVector3Float32FromRef = function (vector3, byteOffset) {
  1334. if (byteOffset + 8 > this._byteOffset) {
  1335. BABYLON.Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!");
  1336. }
  1337. else {
  1338. vector3.x = this._dataView.getFloat32(byteOffset, true);
  1339. vector3.y = this._dataView.getFloat32(byteOffset + 4, true);
  1340. vector3.z = this._dataView.getFloat32(byteOffset + 8, true);
  1341. }
  1342. };
  1343. _BinaryWriter.prototype.setVector3Float32FromRef = function (vector3, byteOffset) {
  1344. if (byteOffset + 8 > this._byteOffset) {
  1345. BABYLON.Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!");
  1346. }
  1347. else {
  1348. this._dataView.setFloat32(byteOffset, vector3.x, true);
  1349. this._dataView.setFloat32(byteOffset + 4, vector3.y, true);
  1350. this._dataView.setFloat32(byteOffset + 8, vector3.z, true);
  1351. }
  1352. };
  1353. _BinaryWriter.prototype.getVector4Float32FromRef = function (vector4, byteOffset) {
  1354. if (byteOffset + 12 > this._byteOffset) {
  1355. BABYLON.Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!");
  1356. }
  1357. else {
  1358. vector4.x = this._dataView.getFloat32(byteOffset, true);
  1359. vector4.y = this._dataView.getFloat32(byteOffset + 4, true);
  1360. vector4.z = this._dataView.getFloat32(byteOffset + 8, true);
  1361. vector4.w = this._dataView.getFloat32(byteOffset + 12, true);
  1362. }
  1363. };
  1364. _BinaryWriter.prototype.setVector4Float32FromRef = function (vector4, byteOffset) {
  1365. if (byteOffset + 12 > this._byteOffset) {
  1366. BABYLON.Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!");
  1367. }
  1368. else {
  1369. this._dataView.setFloat32(byteOffset, vector4.x, true);
  1370. this._dataView.setFloat32(byteOffset + 4, vector4.y, true);
  1371. this._dataView.setFloat32(byteOffset + 8, vector4.z, true);
  1372. this._dataView.setFloat32(byteOffset + 12, vector4.w, true);
  1373. }
  1374. };
  1375. /**
  1376. * Stores a Float32 in the array buffer
  1377. * @param entry
  1378. */
  1379. _BinaryWriter.prototype.setFloat32 = function (entry, byteOffset) {
  1380. if (isNaN(entry)) {
  1381. BABYLON.Tools.Error('Invalid data being written!');
  1382. }
  1383. if (byteOffset != null) {
  1384. if (byteOffset < this._byteOffset) {
  1385. this._dataView.setFloat32(byteOffset, entry, true);
  1386. }
  1387. else {
  1388. BABYLON.Tools.Error('BinaryWriter: byteoffset is greater than the current binary length!');
  1389. }
  1390. }
  1391. if (this._byteOffset + 4 > this._arrayBuffer.byteLength) {
  1392. this.resizeBuffer(this._arrayBuffer.byteLength * 2);
  1393. }
  1394. this._dataView.setFloat32(this._byteOffset, entry, true);
  1395. this._byteOffset += 4;
  1396. };
  1397. /**
  1398. * Stores an UInt32 in the array buffer
  1399. * @param entry
  1400. * @param byteOffset If defined, specifies where to set the value as an offset.
  1401. */
  1402. _BinaryWriter.prototype.setUInt32 = function (entry, byteOffset) {
  1403. if (byteOffset != null) {
  1404. if (byteOffset < this._byteOffset) {
  1405. this._dataView.setUint32(byteOffset, entry, true);
  1406. }
  1407. else {
  1408. BABYLON.Tools.Error('BinaryWriter: byteoffset is greater than the current binary buffer length!');
  1409. }
  1410. }
  1411. else {
  1412. if (this._byteOffset + 4 > this._arrayBuffer.byteLength) {
  1413. this.resizeBuffer(this._arrayBuffer.byteLength * 2);
  1414. }
  1415. this._dataView.setUint32(this._byteOffset, entry, true);
  1416. this._byteOffset += 4;
  1417. }
  1418. };
  1419. return _BinaryWriter;
  1420. }());
  1421. Exporter._BinaryWriter = _BinaryWriter;
  1422. })(Exporter = GLTF2.Exporter || (GLTF2.Exporter = {}));
  1423. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1424. })(BABYLON || (BABYLON = {}));
  1425. //# sourceMappingURL=babylon.glTFExporter.js.map
  1426. /// <reference path="../../../../dist/preview release/glTF2Interface/babylon.glTF2Interface.d.ts"/>
  1427. var BABYLON;
  1428. (function (BABYLON) {
  1429. /**
  1430. * Class for holding and downloading glTF file data
  1431. */
  1432. var GLTFData = /** @class */ (function () {
  1433. /**
  1434. * Initializes the glTF file object
  1435. */
  1436. function GLTFData() {
  1437. this.glTFFiles = {};
  1438. }
  1439. /**
  1440. * Downloads the glTF data as files based on their names and data
  1441. */
  1442. GLTFData.prototype.downloadFiles = function () {
  1443. /**
  1444. * Checks for a matching suffix at the end of a string (for ES5 and lower)
  1445. * @param str Source string
  1446. * @param suffix Suffix to search for in the source string
  1447. * @returns Boolean indicating whether the suffix was found (true) or not (false)
  1448. */
  1449. function endsWith(str, suffix) {
  1450. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  1451. }
  1452. for (var key in this.glTFFiles) {
  1453. var link = document.createElement('a');
  1454. document.body.appendChild(link);
  1455. link.setAttribute("type", "hidden");
  1456. link.download = key;
  1457. var blob = this.glTFFiles[key];
  1458. var mimeType = void 0;
  1459. if (endsWith(key, ".glb")) {
  1460. mimeType = { type: "model/gltf-binary" };
  1461. }
  1462. else if (endsWith(key, ".bin")) {
  1463. mimeType = { type: "application/octet-stream" };
  1464. }
  1465. else if (endsWith(key, ".gltf")) {
  1466. mimeType = { type: "model/gltf+json" };
  1467. }
  1468. else if (endsWith(key, ".jpeg" || ".jpg")) {
  1469. mimeType = { type: "image/jpeg" /* JPEG */ };
  1470. }
  1471. else if (endsWith(key, ".png")) {
  1472. mimeType = { type: "image/png" /* PNG */ };
  1473. }
  1474. link.href = window.URL.createObjectURL(new Blob([blob], mimeType));
  1475. link.click();
  1476. }
  1477. };
  1478. return GLTFData;
  1479. }());
  1480. BABYLON.GLTFData = GLTFData;
  1481. })(BABYLON || (BABYLON = {}));
  1482. //# sourceMappingURL=babylon.glTFData.js.map
  1483. /// <reference path="../../../../dist/preview release/glTF2Interface/babylon.glTF2Interface.d.ts"/>
  1484. var BABYLON;
  1485. (function (BABYLON) {
  1486. var GLTF2;
  1487. (function (GLTF2) {
  1488. var Exporter;
  1489. (function (Exporter) {
  1490. /**
  1491. * Utility methods for working with glTF material conversion properties. This class should only be used internally
  1492. * @hidden
  1493. */
  1494. var _GLTFMaterialExporter = /** @class */ (function () {
  1495. function _GLTFMaterialExporter(exporter) {
  1496. /**
  1497. * Mapping to store textures
  1498. */
  1499. this._textureMap = {};
  1500. this._textureMap = {};
  1501. this._exporter = exporter;
  1502. }
  1503. /**
  1504. * Specifies if two colors are approximately equal in value
  1505. * @param color1 first color to compare to
  1506. * @param color2 second color to compare to
  1507. * @param epsilon threshold value
  1508. */
  1509. _GLTFMaterialExporter.FuzzyEquals = function (color1, color2, epsilon) {
  1510. return BABYLON.Scalar.WithinEpsilon(color1.r, color2.r, epsilon) &&
  1511. BABYLON.Scalar.WithinEpsilon(color1.g, color2.g, epsilon) &&
  1512. BABYLON.Scalar.WithinEpsilon(color1.b, color2.b, epsilon);
  1513. };
  1514. /**
  1515. * Gets the materials from a Babylon scene and converts them to glTF materials
  1516. * @param scene babylonjs scene
  1517. * @param mimeType texture mime type
  1518. * @param images array of images
  1519. * @param textures array of textures
  1520. * @param materials array of materials
  1521. * @param imageData mapping of texture names to base64 textures
  1522. * @param hasTextureCoords specifies if texture coordinates are present on the material
  1523. */
  1524. _GLTFMaterialExporter.prototype._convertMaterialsToGLTFAsync = function (babylonMaterials, mimeType, hasTextureCoords) {
  1525. var promises = [];
  1526. for (var _i = 0, babylonMaterials_1 = babylonMaterials; _i < babylonMaterials_1.length; _i++) {
  1527. var babylonMaterial = babylonMaterials_1[_i];
  1528. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  1529. promises.push(this._convertStandardMaterialAsync(babylonMaterial, mimeType, hasTextureCoords));
  1530. }
  1531. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  1532. promises.push(this._convertPBRMetallicRoughnessMaterialAsync(babylonMaterial, mimeType, hasTextureCoords));
  1533. }
  1534. else if (babylonMaterial instanceof BABYLON.PBRMaterial) {
  1535. promises.push(this._convertPBRMaterialAsync(babylonMaterial, mimeType, hasTextureCoords));
  1536. }
  1537. else {
  1538. BABYLON.Tools.Warn("Unsupported material type: " + babylonMaterial.name);
  1539. }
  1540. }
  1541. return Promise.all(promises).then(function () { });
  1542. };
  1543. /**
  1544. * Makes a copy of the glTF material without the texture parameters
  1545. * @param originalMaterial original glTF material
  1546. * @returns glTF material without texture parameters
  1547. */
  1548. _GLTFMaterialExporter.prototype._stripTexturesFromMaterial = function (originalMaterial) {
  1549. var newMaterial = {};
  1550. if (originalMaterial) {
  1551. newMaterial.name = originalMaterial.name;
  1552. newMaterial.doubleSided = originalMaterial.doubleSided;
  1553. newMaterial.alphaMode = originalMaterial.alphaMode;
  1554. newMaterial.alphaCutoff = originalMaterial.alphaCutoff;
  1555. newMaterial.emissiveFactor = originalMaterial.emissiveFactor;
  1556. var originalPBRMetallicRoughness = originalMaterial.pbrMetallicRoughness;
  1557. if (originalPBRMetallicRoughness) {
  1558. newMaterial.pbrMetallicRoughness = {};
  1559. newMaterial.pbrMetallicRoughness.baseColorFactor = originalPBRMetallicRoughness.baseColorFactor;
  1560. newMaterial.pbrMetallicRoughness.metallicFactor = originalPBRMetallicRoughness.metallicFactor;
  1561. newMaterial.pbrMetallicRoughness.roughnessFactor = originalPBRMetallicRoughness.roughnessFactor;
  1562. }
  1563. }
  1564. return newMaterial;
  1565. };
  1566. /**
  1567. * Specifies if the material has any texture parameters present
  1568. * @param material glTF Material
  1569. * @returns boolean specifying if texture parameters are present
  1570. */
  1571. _GLTFMaterialExporter.prototype._hasTexturesPresent = function (material) {
  1572. if (material.emissiveTexture || material.normalTexture || material.occlusionTexture) {
  1573. return true;
  1574. }
  1575. var pbrMat = material.pbrMetallicRoughness;
  1576. if (pbrMat) {
  1577. if (pbrMat.baseColorTexture || pbrMat.metallicRoughnessTexture) {
  1578. return true;
  1579. }
  1580. }
  1581. return false;
  1582. };
  1583. /**
  1584. * Converts a Babylon StandardMaterial to a glTF Metallic Roughness Material
  1585. * @param babylonStandardMaterial
  1586. * @returns glTF Metallic Roughness Material representation
  1587. */
  1588. _GLTFMaterialExporter.prototype._convertToGLTFPBRMetallicRoughness = function (babylonStandardMaterial) {
  1589. var P0 = new BABYLON.Vector2(0, 1);
  1590. var P1 = new BABYLON.Vector2(0, 0.1);
  1591. var P2 = new BABYLON.Vector2(0, 0.1);
  1592. var P3 = new BABYLON.Vector2(1300, 0.1);
  1593. /**
  1594. * Given the control points, solve for x based on a given t for a cubic bezier curve
  1595. * @param t a value between 0 and 1
  1596. * @param p0 first control point
  1597. * @param p1 second control point
  1598. * @param p2 third control point
  1599. * @param p3 fourth control point
  1600. * @returns number result of cubic bezier curve at the specified t
  1601. */
  1602. function _cubicBezierCurve(t, p0, p1, p2, p3) {
  1603. return ((1 - t) * (1 - t) * (1 - t) * p0 +
  1604. 3 * (1 - t) * (1 - t) * t * p1 +
  1605. 3 * (1 - t) * t * t * p2 +
  1606. t * t * t * p3);
  1607. }
  1608. /**
  1609. * Evaluates a specified specular power value to determine the appropriate roughness value,
  1610. * based on a pre-defined cubic bezier curve with specular on the abscissa axis (x-axis)
  1611. * and roughness on the ordinant axis (y-axis)
  1612. * @param specularPower specular power of standard material
  1613. * @returns Number representing the roughness value
  1614. */
  1615. function _solveForRoughness(specularPower) {
  1616. var t = Math.pow(specularPower / P3.x, 0.333333);
  1617. return _cubicBezierCurve(t, P0.y, P1.y, P2.y, P3.y);
  1618. }
  1619. var diffuse = babylonStandardMaterial.diffuseColor.toLinearSpace().scale(0.5);
  1620. var opacity = babylonStandardMaterial.alpha;
  1621. var specularPower = BABYLON.Scalar.Clamp(babylonStandardMaterial.specularPower, 0, _GLTFMaterialExporter._MaxSpecularPower);
  1622. var roughness = _solveForRoughness(specularPower);
  1623. var glTFPbrMetallicRoughness = {
  1624. baseColorFactor: [
  1625. diffuse.r,
  1626. diffuse.g,
  1627. diffuse.b,
  1628. opacity
  1629. ],
  1630. metallicFactor: 0,
  1631. roughnessFactor: roughness,
  1632. };
  1633. return glTFPbrMetallicRoughness;
  1634. };
  1635. /**
  1636. * Computes the metallic factor
  1637. * @param diffuse diffused value
  1638. * @param specular specular value
  1639. * @param oneMinusSpecularStrength one minus the specular strength
  1640. * @returns metallic value
  1641. */
  1642. _GLTFMaterialExporter._SolveMetallic = function (diffuse, specular, oneMinusSpecularStrength) {
  1643. if (specular < this._DielectricSpecular.r) {
  1644. this._DielectricSpecular;
  1645. return 0;
  1646. }
  1647. var a = this._DielectricSpecular.r;
  1648. var b = diffuse * oneMinusSpecularStrength / (1.0 - this._DielectricSpecular.r) + specular - 2.0 * this._DielectricSpecular.r;
  1649. var c = this._DielectricSpecular.r - specular;
  1650. var D = b * b - 4.0 * a * c;
  1651. return BABYLON.Scalar.Clamp((-b + Math.sqrt(D)) / (2.0 * a), 0, 1);
  1652. };
  1653. /**
  1654. * Gets the glTF alpha mode from the Babylon Material
  1655. * @param babylonMaterial Babylon Material
  1656. * @returns The Babylon alpha mode value
  1657. */
  1658. _GLTFMaterialExporter.prototype._getAlphaMode = function (babylonMaterial) {
  1659. if (babylonMaterial.needAlphaBlending()) {
  1660. return "BLEND" /* BLEND */;
  1661. }
  1662. else if (babylonMaterial.needAlphaTesting()) {
  1663. return "MASK" /* MASK */;
  1664. }
  1665. else {
  1666. return "OPAQUE" /* OPAQUE */;
  1667. }
  1668. };
  1669. /**
  1670. * Converts a Babylon Standard Material to a glTF Material
  1671. * @param babylonStandardMaterial BJS Standard Material
  1672. * @param mimeType mime type to use for the textures
  1673. * @param images array of glTF image interfaces
  1674. * @param textures array of glTF texture interfaces
  1675. * @param materials array of glTF material interfaces
  1676. * @param imageData map of image file name to data
  1677. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  1678. */
  1679. _GLTFMaterialExporter.prototype._convertStandardMaterialAsync = function (babylonStandardMaterial, mimeType, hasTextureCoords) {
  1680. var materialMap = this._exporter._materialMap;
  1681. var materials = this._exporter._materials;
  1682. var alphaMode = this._getAlphaMode(babylonStandardMaterial);
  1683. var promises = [];
  1684. var glTFPbrMetallicRoughness = this._convertToGLTFPBRMetallicRoughness(babylonStandardMaterial);
  1685. var glTFMaterial = { name: babylonStandardMaterial.name };
  1686. if (babylonStandardMaterial.backFaceCulling != null && !babylonStandardMaterial.backFaceCulling) {
  1687. if (!babylonStandardMaterial.twoSidedLighting) {
  1688. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  1689. }
  1690. glTFMaterial.doubleSided = true;
  1691. }
  1692. if (hasTextureCoords) {
  1693. if (babylonStandardMaterial.diffuseTexture) {
  1694. promises.push(this._exportTextureAsync(babylonStandardMaterial.diffuseTexture, mimeType).then(function (glTFTexture) {
  1695. if (glTFTexture) {
  1696. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1697. }
  1698. }));
  1699. }
  1700. if (babylonStandardMaterial.bumpTexture) {
  1701. promises.push(this._exportTextureAsync(babylonStandardMaterial.bumpTexture, mimeType).then(function (glTFTexture) {
  1702. if (glTFTexture) {
  1703. glTFMaterial.normalTexture = glTFTexture;
  1704. if (babylonStandardMaterial.bumpTexture != null && babylonStandardMaterial.bumpTexture.level !== 1) {
  1705. glTFMaterial.normalTexture.scale = babylonStandardMaterial.bumpTexture.level;
  1706. }
  1707. }
  1708. }));
  1709. }
  1710. if (babylonStandardMaterial.emissiveTexture) {
  1711. glTFMaterial.emissiveFactor = [1.0, 1.0, 1.0];
  1712. promises.push(this._exportTextureAsync(babylonStandardMaterial.emissiveTexture, mimeType).then(function (glTFEmissiveTexture) {
  1713. if (glTFEmissiveTexture) {
  1714. glTFMaterial.emissiveTexture = glTFEmissiveTexture;
  1715. }
  1716. }));
  1717. }
  1718. if (babylonStandardMaterial.ambientTexture) {
  1719. promises.push(this._exportTextureAsync(babylonStandardMaterial.ambientTexture, mimeType).then(function (glTFTexture) {
  1720. if (glTFTexture) {
  1721. var occlusionTexture = {
  1722. index: glTFTexture.index
  1723. };
  1724. glTFMaterial.occlusionTexture = occlusionTexture;
  1725. occlusionTexture.strength = 1.0;
  1726. }
  1727. }));
  1728. }
  1729. }
  1730. if (babylonStandardMaterial.alpha < 1.0 || babylonStandardMaterial.opacityTexture) {
  1731. if (babylonStandardMaterial.alphaMode === BABYLON.Engine.ALPHA_COMBINE) {
  1732. glTFMaterial.alphaMode = "BLEND" /* BLEND */;
  1733. }
  1734. else {
  1735. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": glTF 2.0 does not support alpha mode: " + babylonStandardMaterial.alphaMode.toString());
  1736. }
  1737. }
  1738. if (babylonStandardMaterial.emissiveColor && !_GLTFMaterialExporter.FuzzyEquals(babylonStandardMaterial.emissiveColor, BABYLON.Color3.Black(), _GLTFMaterialExporter._Epsilon)) {
  1739. glTFMaterial.emissiveFactor = babylonStandardMaterial.emissiveColor.asArray();
  1740. }
  1741. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1742. if (alphaMode !== "OPAQUE" /* OPAQUE */) {
  1743. switch (alphaMode) {
  1744. case "BLEND" /* BLEND */: {
  1745. glTFMaterial.alphaMode = "BLEND" /* BLEND */;
  1746. break;
  1747. }
  1748. case "MASK" /* MASK */: {
  1749. glTFMaterial.alphaMode = "MASK" /* MASK */;
  1750. glTFMaterial.alphaCutoff = babylonStandardMaterial.alphaCutOff;
  1751. break;
  1752. }
  1753. default: {
  1754. BABYLON.Tools.Warn("Unsupported alpha mode " + alphaMode);
  1755. }
  1756. }
  1757. }
  1758. materials.push(glTFMaterial);
  1759. materialMap[babylonStandardMaterial.uniqueId] = materials.length - 1;
  1760. return Promise.all(promises).then(function () { });
  1761. };
  1762. /**
  1763. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material
  1764. * @param babylonPBRMetalRoughMaterial BJS PBR Metallic Roughness Material
  1765. * @param mimeType mime type to use for the textures
  1766. * @param images array of glTF image interfaces
  1767. * @param textures array of glTF texture interfaces
  1768. * @param materials array of glTF material interfaces
  1769. * @param imageData map of image file name to data
  1770. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  1771. */
  1772. _GLTFMaterialExporter.prototype._convertPBRMetallicRoughnessMaterialAsync = function (babylonPBRMetalRoughMaterial, mimeType, hasTextureCoords) {
  1773. var materialMap = this._exporter._materialMap;
  1774. var materials = this._exporter._materials;
  1775. var promises = [];
  1776. var glTFPbrMetallicRoughness = {};
  1777. if (babylonPBRMetalRoughMaterial.baseColor) {
  1778. glTFPbrMetallicRoughness.baseColorFactor = [
  1779. babylonPBRMetalRoughMaterial.baseColor.r,
  1780. babylonPBRMetalRoughMaterial.baseColor.g,
  1781. babylonPBRMetalRoughMaterial.baseColor.b,
  1782. babylonPBRMetalRoughMaterial.alpha
  1783. ];
  1784. }
  1785. if (babylonPBRMetalRoughMaterial.metallic != null && babylonPBRMetalRoughMaterial.metallic !== 1) {
  1786. glTFPbrMetallicRoughness.metallicFactor = babylonPBRMetalRoughMaterial.metallic;
  1787. }
  1788. if (babylonPBRMetalRoughMaterial.roughness != null && babylonPBRMetalRoughMaterial.roughness !== 1) {
  1789. glTFPbrMetallicRoughness.roughnessFactor = babylonPBRMetalRoughMaterial.roughness;
  1790. }
  1791. var glTFMaterial = {
  1792. name: babylonPBRMetalRoughMaterial.name
  1793. };
  1794. if (babylonPBRMetalRoughMaterial.doubleSided) {
  1795. glTFMaterial.doubleSided = babylonPBRMetalRoughMaterial.doubleSided;
  1796. }
  1797. var alphaMode = null;
  1798. if (babylonPBRMetalRoughMaterial.transparencyMode != null) {
  1799. alphaMode = this._getAlphaMode(babylonPBRMetalRoughMaterial);
  1800. if (alphaMode) {
  1801. if (alphaMode !== "OPAQUE" /* OPAQUE */) { //glTF defaults to opaque
  1802. glTFMaterial.alphaMode = alphaMode;
  1803. if (alphaMode === "MASK" /* MASK */) {
  1804. glTFMaterial.alphaCutoff = babylonPBRMetalRoughMaterial.alphaCutOff;
  1805. }
  1806. }
  1807. }
  1808. }
  1809. if (hasTextureCoords) {
  1810. if (babylonPBRMetalRoughMaterial.baseTexture != null) {
  1811. promises.push(this._exportTextureAsync(babylonPBRMetalRoughMaterial.baseTexture, mimeType).then(function (glTFTexture) {
  1812. if (glTFTexture) {
  1813. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1814. }
  1815. }));
  1816. }
  1817. if (babylonPBRMetalRoughMaterial.normalTexture) {
  1818. promises.push(this._exportTextureAsync(babylonPBRMetalRoughMaterial.normalTexture, mimeType).then(function (glTFTexture) {
  1819. if (glTFTexture) {
  1820. glTFMaterial.normalTexture = glTFTexture;
  1821. if (babylonPBRMetalRoughMaterial.normalTexture.level !== 1) {
  1822. glTFMaterial.normalTexture.scale = babylonPBRMetalRoughMaterial.normalTexture.level;
  1823. }
  1824. }
  1825. }));
  1826. }
  1827. if (babylonPBRMetalRoughMaterial.occlusionTexture) {
  1828. promises.push(this._exportTextureAsync(babylonPBRMetalRoughMaterial.occlusionTexture, mimeType).then(function (glTFTexture) {
  1829. if (glTFTexture) {
  1830. glTFMaterial.occlusionTexture = glTFTexture;
  1831. if (babylonPBRMetalRoughMaterial.occlusionStrength != null) {
  1832. glTFMaterial.occlusionTexture.strength = babylonPBRMetalRoughMaterial.occlusionStrength;
  1833. }
  1834. }
  1835. }));
  1836. }
  1837. if (babylonPBRMetalRoughMaterial.emissiveTexture) {
  1838. promises.push(this._exportTextureAsync(babylonPBRMetalRoughMaterial.emissiveTexture, mimeType).then(function (glTFTexture) {
  1839. if (glTFTexture) {
  1840. glTFMaterial.emissiveTexture = glTFTexture;
  1841. }
  1842. }));
  1843. }
  1844. }
  1845. if (_GLTFMaterialExporter.FuzzyEquals(babylonPBRMetalRoughMaterial.emissiveColor, BABYLON.Color3.Black(), _GLTFMaterialExporter._Epsilon)) {
  1846. glTFMaterial.emissiveFactor = babylonPBRMetalRoughMaterial.emissiveColor.asArray();
  1847. }
  1848. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1849. materials.push(glTFMaterial);
  1850. materialMap[babylonPBRMetalRoughMaterial.uniqueId] = materials.length - 1;
  1851. return Promise.all(promises).then(function () { });
  1852. };
  1853. /**
  1854. * Converts an image typed array buffer to a base64 image
  1855. * @param buffer typed array buffer
  1856. * @param width width of the image
  1857. * @param height height of the image
  1858. * @param mimeType mimetype of the image
  1859. * @returns base64 image string
  1860. */
  1861. _GLTFMaterialExporter.prototype._createBase64FromCanvasAsync = function (buffer, width, height, mimeType) {
  1862. var _this = this;
  1863. return new Promise(function (resolve, reject) {
  1864. var hostingScene;
  1865. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  1866. var engine = _this._exporter._getLocalEngine();
  1867. hostingScene = new BABYLON.Scene(engine);
  1868. // Create a temporary texture with the texture buffer data
  1869. var tempTexture = engine.createRawTexture(buffer, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, true, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  1870. var postProcess = new BABYLON.PostProcess("pass", "pass", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  1871. postProcess.getEffect().executeWhenCompiled(function () {
  1872. postProcess.onApply = function (effect) {
  1873. effect._bindTexture("textureSampler", tempTexture);
  1874. };
  1875. // Set the size of the texture
  1876. engine.setSize(width, height);
  1877. hostingScene.postProcessManager.directRender([postProcess], null);
  1878. postProcess.dispose();
  1879. tempTexture.dispose();
  1880. // Read data from WebGL
  1881. var canvas = engine.getRenderingCanvas();
  1882. if (canvas) {
  1883. if (!canvas.toBlob) { // fallback for browsers without "canvas.toBlob"
  1884. var dataURL = canvas.toDataURL();
  1885. resolve(dataURL);
  1886. }
  1887. else {
  1888. BABYLON.Tools.ToBlob(canvas, function (blob) {
  1889. if (blob) {
  1890. var fileReader = new FileReader();
  1891. fileReader.onload = function (event) {
  1892. var base64String = event.target.result;
  1893. hostingScene.dispose();
  1894. resolve(base64String);
  1895. };
  1896. fileReader.readAsDataURL(blob);
  1897. }
  1898. else {
  1899. reject("gltfMaterialExporter: Failed to get blob from image canvas!");
  1900. }
  1901. });
  1902. }
  1903. }
  1904. else {
  1905. reject("Engine is missing a canvas!");
  1906. }
  1907. });
  1908. });
  1909. };
  1910. /**
  1911. * Generates a white texture based on the specified width and height
  1912. * @param width width of the texture in pixels
  1913. * @param height height of the texture in pixels
  1914. * @param scene babylonjs scene
  1915. * @returns white texture
  1916. */
  1917. _GLTFMaterialExporter.prototype._createWhiteTexture = function (width, height, scene) {
  1918. var data = new Uint8Array(width * height * 4);
  1919. for (var i = 0; i < data.length; i = i + 4) {
  1920. data[i] = data[i + 1] = data[i + 2] = data[i + 3] = 0xFF;
  1921. }
  1922. var rawTexture = BABYLON.RawTexture.CreateRGBATexture(data, width, height, scene);
  1923. return rawTexture;
  1924. };
  1925. /**
  1926. * Resizes the two source textures to the same dimensions. If a texture is null, a default white texture is generated. If both textures are null, returns null
  1927. * @param texture1 first texture to resize
  1928. * @param texture2 second texture to resize
  1929. * @param scene babylonjs scene
  1930. * @returns resized textures or null
  1931. */
  1932. _GLTFMaterialExporter.prototype._resizeTexturesToSameDimensions = function (texture1, texture2, scene) {
  1933. var texture1Size = texture1 ? texture1.getSize() : { width: 0, height: 0 };
  1934. var texture2Size = texture2 ? texture2.getSize() : { width: 0, height: 0 };
  1935. var resizedTexture1;
  1936. var resizedTexture2;
  1937. if (texture1Size.width < texture2Size.width) {
  1938. if (texture1 && texture1 instanceof BABYLON.Texture) {
  1939. resizedTexture1 = BABYLON.TextureTools.CreateResizedCopy(texture1, texture2Size.width, texture2Size.height, true);
  1940. }
  1941. else {
  1942. resizedTexture1 = this._createWhiteTexture(texture2Size.width, texture2Size.height, scene);
  1943. }
  1944. resizedTexture2 = texture2;
  1945. }
  1946. else if (texture1Size.width > texture2Size.width) {
  1947. if (texture2 && texture2 instanceof BABYLON.Texture) {
  1948. resizedTexture2 = BABYLON.TextureTools.CreateResizedCopy(texture2, texture1Size.width, texture1Size.height, true);
  1949. }
  1950. else {
  1951. resizedTexture2 = this._createWhiteTexture(texture1Size.width, texture1Size.height, scene);
  1952. }
  1953. resizedTexture1 = texture1;
  1954. }
  1955. else {
  1956. resizedTexture1 = texture1;
  1957. resizedTexture2 = texture2;
  1958. }
  1959. return {
  1960. "texture1": resizedTexture1,
  1961. "texture2": resizedTexture2
  1962. };
  1963. };
  1964. /**
  1965. * Converts an array of pixels to a Float32Array
  1966. * Throws an error if the pixel format is not supported
  1967. * @param pixels - array buffer containing pixel values
  1968. * @returns Float32 of pixels
  1969. */
  1970. _GLTFMaterialExporter.prototype._convertPixelArrayToFloat32 = function (pixels) {
  1971. if (pixels instanceof Uint8Array) {
  1972. var length_1 = pixels.length;
  1973. var buffer = new Float32Array(pixels.length);
  1974. for (var i = 0; i < length_1; ++i) {
  1975. buffer[i] = pixels[i] / 255;
  1976. }
  1977. return buffer;
  1978. }
  1979. else if (pixels instanceof Float32Array) {
  1980. return pixels;
  1981. }
  1982. else {
  1983. throw new Error('Unsupported pixel format!');
  1984. }
  1985. };
  1986. /**
  1987. * Convert Specular Glossiness Textures to Metallic Roughness
  1988. * See link below for info on the material conversions from PBR Metallic/Roughness and Specular/Glossiness
  1989. * @link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness/examples/convert-between-workflows-bjs/js/babylon.pbrUtilities.js
  1990. * @param diffuseTexture texture used to store diffuse information
  1991. * @param specularGlossinessTexture texture used to store specular and glossiness information
  1992. * @param factors specular glossiness material factors
  1993. * @param mimeType the mime type to use for the texture
  1994. * @returns pbr metallic roughness interface or null
  1995. */
  1996. _GLTFMaterialExporter.prototype._convertSpecularGlossinessTexturesToMetallicRoughnessAsync = function (diffuseTexture, specularGlossinessTexture, factors, mimeType) {
  1997. var promises = [];
  1998. if (!(diffuseTexture || specularGlossinessTexture)) {
  1999. return Promise.reject('_ConvertSpecularGlosinessTexturesToMetallicRoughness: diffuse and specular glossiness textures are not defined!');
  2000. }
  2001. var scene = diffuseTexture ? diffuseTexture.getScene() : specularGlossinessTexture ? specularGlossinessTexture.getScene() : null;
  2002. if (scene) {
  2003. var resizedTextures = this._resizeTexturesToSameDimensions(diffuseTexture, specularGlossinessTexture, scene);
  2004. var diffuseSize = resizedTextures.texture1.getSize();
  2005. var diffuseBuffer = void 0;
  2006. var specularGlossinessBuffer = void 0;
  2007. var width = diffuseSize.width;
  2008. var height = diffuseSize.height;
  2009. var diffusePixels = resizedTextures.texture1.readPixels();
  2010. var specularPixels = resizedTextures.texture2.readPixels();
  2011. if (diffusePixels) {
  2012. diffuseBuffer = this._convertPixelArrayToFloat32(diffusePixels);
  2013. }
  2014. else {
  2015. return Promise.reject("Failed to retrieve pixels from diffuse texture!");
  2016. }
  2017. if (specularPixels) {
  2018. specularGlossinessBuffer = this._convertPixelArrayToFloat32(specularPixels);
  2019. }
  2020. else {
  2021. return Promise.reject("Failed to retrieve pixels from specular glossiness texture!");
  2022. }
  2023. var byteLength = specularGlossinessBuffer.byteLength;
  2024. var metallicRoughnessBuffer = new Uint8Array(byteLength);
  2025. var baseColorBuffer = new Uint8Array(byteLength);
  2026. var strideSize = 4;
  2027. var maxBaseColor = BABYLON.Color3.Black();
  2028. var maxMetallic = 0;
  2029. var maxRoughness = 0;
  2030. for (var h = 0; h < height; ++h) {
  2031. for (var w = 0; w < width; ++w) {
  2032. var offset = (width * h + w) * strideSize;
  2033. var diffuseColor = new BABYLON.Color3(diffuseBuffer[offset], diffuseBuffer[offset + 1], diffuseBuffer[offset + 2]).toLinearSpace().multiply(factors.diffuseColor);
  2034. var specularColor = new BABYLON.Color3(specularGlossinessBuffer[offset], specularGlossinessBuffer[offset + 1], specularGlossinessBuffer[offset + 2]).toLinearSpace().multiply(factors.specularColor);
  2035. var glossiness = (specularGlossinessBuffer[offset + 3]) * factors.glossiness;
  2036. var specularGlossiness = {
  2037. diffuseColor: diffuseColor,
  2038. specularColor: specularColor,
  2039. glossiness: glossiness
  2040. };
  2041. var metallicRoughness = this._convertSpecularGlossinessToMetallicRoughness(specularGlossiness);
  2042. maxBaseColor.r = Math.max(maxBaseColor.r, metallicRoughness.baseColor.r);
  2043. maxBaseColor.g = Math.max(maxBaseColor.g, metallicRoughness.baseColor.g);
  2044. maxBaseColor.b = Math.max(maxBaseColor.b, metallicRoughness.baseColor.b);
  2045. maxMetallic = Math.max(maxMetallic, metallicRoughness.metallic);
  2046. maxRoughness = Math.max(maxRoughness, metallicRoughness.roughness);
  2047. baseColorBuffer[offset] = metallicRoughness.baseColor.r * 255;
  2048. baseColorBuffer[offset + 1] = metallicRoughness.baseColor.g * 255;
  2049. baseColorBuffer[offset + 2] = metallicRoughness.baseColor.b * 255;
  2050. baseColorBuffer[offset + 3] = resizedTextures.texture1.hasAlpha ? diffuseBuffer[offset + 3] * 255 : 255;
  2051. metallicRoughnessBuffer[offset] = 0;
  2052. metallicRoughnessBuffer[offset + 1] = metallicRoughness.roughness * 255;
  2053. metallicRoughnessBuffer[offset + 2] = metallicRoughness.metallic * 255;
  2054. metallicRoughnessBuffer[offset + 3] = 255;
  2055. }
  2056. }
  2057. // Retrieves the metallic roughness factors from the maximum texture values.
  2058. var metallicRoughnessFactors_1 = {
  2059. baseColor: maxBaseColor,
  2060. metallic: maxMetallic,
  2061. roughness: maxRoughness
  2062. };
  2063. var writeOutMetallicRoughnessTexture = false;
  2064. var writeOutBaseColorTexture = false;
  2065. for (var h = 0; h < height; ++h) {
  2066. for (var w = 0; w < width; ++w) {
  2067. var destinationOffset = (width * h + w) * strideSize;
  2068. baseColorBuffer[destinationOffset] /= metallicRoughnessFactors_1.baseColor.r > _GLTFMaterialExporter._Epsilon ? metallicRoughnessFactors_1.baseColor.r : 1;
  2069. baseColorBuffer[destinationOffset + 1] /= metallicRoughnessFactors_1.baseColor.g > _GLTFMaterialExporter._Epsilon ? metallicRoughnessFactors_1.baseColor.g : 1;
  2070. baseColorBuffer[destinationOffset + 2] /= metallicRoughnessFactors_1.baseColor.b > _GLTFMaterialExporter._Epsilon ? metallicRoughnessFactors_1.baseColor.b : 1;
  2071. var linearBaseColorPixel = BABYLON.Color3.FromInts(baseColorBuffer[destinationOffset], baseColorBuffer[destinationOffset + 1], baseColorBuffer[destinationOffset + 2]);
  2072. var sRGBBaseColorPixel = linearBaseColorPixel.toGammaSpace();
  2073. baseColorBuffer[destinationOffset] = sRGBBaseColorPixel.r * 255;
  2074. baseColorBuffer[destinationOffset + 1] = sRGBBaseColorPixel.g * 255;
  2075. baseColorBuffer[destinationOffset + 2] = sRGBBaseColorPixel.b * 255;
  2076. if (!_GLTFMaterialExporter.FuzzyEquals(sRGBBaseColorPixel, BABYLON.Color3.White(), _GLTFMaterialExporter._Epsilon)) {
  2077. writeOutBaseColorTexture = true;
  2078. }
  2079. metallicRoughnessBuffer[destinationOffset + 1] /= metallicRoughnessFactors_1.roughness > _GLTFMaterialExporter._Epsilon ? metallicRoughnessFactors_1.roughness : 1;
  2080. metallicRoughnessBuffer[destinationOffset + 2] /= metallicRoughnessFactors_1.metallic > _GLTFMaterialExporter._Epsilon ? metallicRoughnessFactors_1.metallic : 1;
  2081. var metallicRoughnessPixel = BABYLON.Color3.FromInts(255, metallicRoughnessBuffer[destinationOffset + 1], metallicRoughnessBuffer[destinationOffset + 2]);
  2082. if (!_GLTFMaterialExporter.FuzzyEquals(metallicRoughnessPixel, BABYLON.Color3.White(), _GLTFMaterialExporter._Epsilon)) {
  2083. writeOutMetallicRoughnessTexture = true;
  2084. }
  2085. }
  2086. }
  2087. if (writeOutMetallicRoughnessTexture) {
  2088. var promise = this._createBase64FromCanvasAsync(metallicRoughnessBuffer, width, height, mimeType).then(function (metallicRoughnessBase64) {
  2089. metallicRoughnessFactors_1.metallicRoughnessTextureBase64 = metallicRoughnessBase64;
  2090. });
  2091. promises.push(promise);
  2092. }
  2093. if (writeOutBaseColorTexture) {
  2094. var promise = this._createBase64FromCanvasAsync(baseColorBuffer, width, height, mimeType).then(function (baseColorBase64) {
  2095. metallicRoughnessFactors_1.baseColorTextureBase64 = baseColorBase64;
  2096. });
  2097. promises.push(promise);
  2098. }
  2099. return Promise.all(promises).then(function () {
  2100. return metallicRoughnessFactors_1;
  2101. });
  2102. }
  2103. else {
  2104. return Promise.reject("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Scene from textures is missing!");
  2105. }
  2106. };
  2107. /**
  2108. * Converts specular glossiness material properties to metallic roughness
  2109. * @param specularGlossiness interface with specular glossiness material properties
  2110. * @returns interface with metallic roughness material properties
  2111. */
  2112. _GLTFMaterialExporter.prototype._convertSpecularGlossinessToMetallicRoughness = function (specularGlossiness) {
  2113. var diffusePerceivedBrightness = this._getPerceivedBrightness(specularGlossiness.diffuseColor);
  2114. var specularPerceivedBrightness = this._getPerceivedBrightness(specularGlossiness.specularColor);
  2115. var oneMinusSpecularStrength = 1 - this._getMaxComponent(specularGlossiness.specularColor);
  2116. var metallic = _GLTFMaterialExporter._SolveMetallic(diffusePerceivedBrightness, specularPerceivedBrightness, oneMinusSpecularStrength);
  2117. var baseColorFromDiffuse = specularGlossiness.diffuseColor.scale(oneMinusSpecularStrength / (1.0 - _GLTFMaterialExporter._DielectricSpecular.r) / Math.max(1 - metallic, _GLTFMaterialExporter._Epsilon));
  2118. var baseColorFromSpecular = specularGlossiness.specularColor.subtract(_GLTFMaterialExporter._DielectricSpecular.scale(1 - metallic)).scale(1 / Math.max(metallic, _GLTFMaterialExporter._Epsilon));
  2119. var baseColor = BABYLON.Color3.Lerp(baseColorFromDiffuse, baseColorFromSpecular, metallic * metallic);
  2120. baseColor = baseColor.clampToRef(0, 1, baseColor);
  2121. var metallicRoughness = {
  2122. baseColor: baseColor,
  2123. metallic: metallic,
  2124. roughness: 1 - specularGlossiness.glossiness
  2125. };
  2126. return metallicRoughness;
  2127. };
  2128. /**
  2129. * Calculates the surface reflectance, independent of lighting conditions
  2130. * @param color Color source to calculate brightness from
  2131. * @returns number representing the perceived brightness, or zero if color is undefined
  2132. */
  2133. _GLTFMaterialExporter.prototype._getPerceivedBrightness = function (color) {
  2134. if (color) {
  2135. return Math.sqrt(0.299 * color.r * color.r + 0.587 * color.g * color.g + 0.114 * color.b * color.b);
  2136. }
  2137. return 0;
  2138. };
  2139. /**
  2140. * Returns the maximum color component value
  2141. * @param color
  2142. * @returns maximum color component value, or zero if color is null or undefined
  2143. */
  2144. _GLTFMaterialExporter.prototype._getMaxComponent = function (color) {
  2145. if (color) {
  2146. return Math.max(color.r, Math.max(color.g, color.b));
  2147. }
  2148. return 0;
  2149. };
  2150. /**
  2151. * Convert a PBRMaterial (Metallic/Roughness) to Metallic Roughness factors
  2152. * @param babylonPBRMaterial BJS PBR Metallic Roughness Material
  2153. * @param mimeType mime type to use for the textures
  2154. * @param images array of glTF image interfaces
  2155. * @param textures array of glTF texture interfaces
  2156. * @param glTFPbrMetallicRoughness glTF PBR Metallic Roughness interface
  2157. * @param imageData map of image file name to data
  2158. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  2159. * @returns glTF PBR Metallic Roughness factors
  2160. */
  2161. _GLTFMaterialExporter.prototype._convertMetalRoughFactorsToMetallicRoughnessAsync = function (babylonPBRMaterial, mimeType, glTFPbrMetallicRoughness, hasTextureCoords) {
  2162. var promises = [];
  2163. var metallicRoughness = {
  2164. baseColor: babylonPBRMaterial.albedoColor,
  2165. metallic: babylonPBRMaterial.metallic,
  2166. roughness: babylonPBRMaterial.roughness
  2167. };
  2168. if (hasTextureCoords) {
  2169. if (babylonPBRMaterial.albedoTexture) {
  2170. promises.push(this._exportTextureAsync(babylonPBRMaterial.albedoTexture, mimeType).then(function (glTFTexture) {
  2171. if (glTFTexture) {
  2172. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  2173. }
  2174. }));
  2175. }
  2176. if (babylonPBRMaterial.metallicTexture) {
  2177. promises.push(this._exportTextureAsync(babylonPBRMaterial.metallicTexture, mimeType).then(function (glTFTexture) {
  2178. if (glTFTexture) {
  2179. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFTexture;
  2180. }
  2181. }));
  2182. }
  2183. }
  2184. return Promise.all(promises).then(function () {
  2185. return metallicRoughness;
  2186. });
  2187. };
  2188. _GLTFMaterialExporter.prototype._getGLTFTextureSampler = function (texture) {
  2189. var sampler = this._getGLTFTextureWrapModesSampler(texture);
  2190. var samplingMode = texture instanceof BABYLON.Texture ? texture.samplingMode : null;
  2191. if (samplingMode != null) {
  2192. switch (samplingMode) {
  2193. case BABYLON.Texture.LINEAR_LINEAR: {
  2194. sampler.magFilter = 9729 /* LINEAR */;
  2195. sampler.minFilter = 9729 /* LINEAR */;
  2196. break;
  2197. }
  2198. case BABYLON.Texture.LINEAR_NEAREST: {
  2199. sampler.magFilter = 9729 /* LINEAR */;
  2200. sampler.minFilter = 9728 /* NEAREST */;
  2201. break;
  2202. }
  2203. case BABYLON.Texture.NEAREST_LINEAR: {
  2204. sampler.magFilter = 9728 /* NEAREST */;
  2205. sampler.minFilter = 9729 /* LINEAR */;
  2206. break;
  2207. }
  2208. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR: {
  2209. sampler.magFilter = 9728 /* NEAREST */;
  2210. sampler.minFilter = 9987 /* LINEAR_MIPMAP_LINEAR */;
  2211. break;
  2212. }
  2213. case BABYLON.Texture.NEAREST_NEAREST: {
  2214. sampler.magFilter = 9728 /* NEAREST */;
  2215. sampler.minFilter = 9728 /* NEAREST */;
  2216. break;
  2217. }
  2218. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST: {
  2219. sampler.magFilter = 9728 /* NEAREST */;
  2220. sampler.minFilter = 9985 /* LINEAR_MIPMAP_NEAREST */;
  2221. break;
  2222. }
  2223. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST: {
  2224. sampler.magFilter = 9729 /* LINEAR */;
  2225. sampler.minFilter = 9984 /* NEAREST_MIPMAP_NEAREST */;
  2226. break;
  2227. }
  2228. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR: {
  2229. sampler.magFilter = 9729 /* LINEAR */;
  2230. sampler.minFilter = 9986 /* NEAREST_MIPMAP_LINEAR */;
  2231. break;
  2232. }
  2233. case BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR: {
  2234. sampler.magFilter = 9728 /* NEAREST */;
  2235. sampler.minFilter = 9986 /* NEAREST_MIPMAP_LINEAR */;
  2236. break;
  2237. }
  2238. case BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR: {
  2239. sampler.magFilter = 9729 /* LINEAR */;
  2240. sampler.minFilter = 9987 /* LINEAR_MIPMAP_LINEAR */;
  2241. break;
  2242. }
  2243. case BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST: {
  2244. sampler.magFilter = 9729 /* LINEAR */;
  2245. sampler.minFilter = 9985 /* LINEAR_MIPMAP_NEAREST */;
  2246. break;
  2247. }
  2248. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST: {
  2249. sampler.magFilter = 9728 /* NEAREST */;
  2250. sampler.minFilter = 9984 /* NEAREST_MIPMAP_NEAREST */;
  2251. break;
  2252. }
  2253. }
  2254. }
  2255. return sampler;
  2256. };
  2257. _GLTFMaterialExporter.prototype._getGLTFTextureWrapMode = function (wrapMode) {
  2258. switch (wrapMode) {
  2259. case BABYLON.Texture.WRAP_ADDRESSMODE: {
  2260. return 10497 /* REPEAT */;
  2261. }
  2262. case BABYLON.Texture.CLAMP_ADDRESSMODE: {
  2263. return 33071 /* CLAMP_TO_EDGE */;
  2264. }
  2265. case BABYLON.Texture.MIRROR_ADDRESSMODE: {
  2266. return 33648 /* MIRRORED_REPEAT */;
  2267. }
  2268. default: {
  2269. BABYLON.Tools.Error("Unsupported Texture Wrap Mode " + wrapMode + "!");
  2270. return 10497 /* REPEAT */;
  2271. }
  2272. }
  2273. };
  2274. _GLTFMaterialExporter.prototype._getGLTFTextureWrapModesSampler = function (texture) {
  2275. var wrapS = this._getGLTFTextureWrapMode(texture instanceof BABYLON.Texture ? texture.wrapU : BABYLON.Texture.WRAP_ADDRESSMODE);
  2276. var wrapT = this._getGLTFTextureWrapMode(texture instanceof BABYLON.Texture ? texture.wrapV : BABYLON.Texture.WRAP_ADDRESSMODE);
  2277. if (wrapS === 10497 /* REPEAT */ && wrapT === 10497 /* REPEAT */) { // default wrapping mode in glTF, so omitting
  2278. return {};
  2279. }
  2280. return { wrapS: wrapS, wrapT: wrapT };
  2281. };
  2282. /**
  2283. * Convert a PBRMaterial (Specular/Glossiness) to Metallic Roughness factors
  2284. * @param babylonPBRMaterial BJS PBR Metallic Roughness Material
  2285. * @param mimeType mime type to use for the textures
  2286. * @param images array of glTF image interfaces
  2287. * @param textures array of glTF texture interfaces
  2288. * @param glTFPbrMetallicRoughness glTF PBR Metallic Roughness interface
  2289. * @param imageData map of image file name to data
  2290. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  2291. * @returns glTF PBR Metallic Roughness factors
  2292. */
  2293. _GLTFMaterialExporter.prototype._convertSpecGlossFactorsToMetallicRoughnessAsync = function (babylonPBRMaterial, mimeType, glTFPbrMetallicRoughness, hasTextureCoords) {
  2294. var _this = this;
  2295. return Promise.resolve().then(function () {
  2296. var samplers = _this._exporter._samplers;
  2297. var textures = _this._exporter._textures;
  2298. var specGloss = {
  2299. diffuseColor: babylonPBRMaterial.albedoColor || BABYLON.Color3.White(),
  2300. specularColor: babylonPBRMaterial.reflectivityColor || BABYLON.Color3.White(),
  2301. glossiness: babylonPBRMaterial.microSurface || 1,
  2302. };
  2303. var samplerIndex = null;
  2304. var sampler = _this._getGLTFTextureSampler(babylonPBRMaterial.albedoTexture);
  2305. if (sampler.magFilter != null && sampler.minFilter != null && sampler.wrapS != null && sampler.wrapT != null) {
  2306. samplers.push(sampler);
  2307. samplerIndex = samplers.length - 1;
  2308. }
  2309. if (babylonPBRMaterial.reflectivityTexture && !babylonPBRMaterial.useMicroSurfaceFromReflectivityMapAlpha) {
  2310. return Promise.reject("_ConvertPBRMaterial: Glossiness values not included in the reflectivity texture are currently not supported");
  2311. }
  2312. if ((babylonPBRMaterial.albedoTexture || babylonPBRMaterial.reflectivityTexture) && hasTextureCoords) {
  2313. return _this._convertSpecularGlossinessTexturesToMetallicRoughnessAsync(babylonPBRMaterial.albedoTexture, babylonPBRMaterial.reflectivityTexture, specGloss, mimeType).then(function (metallicRoughnessFactors) {
  2314. if (metallicRoughnessFactors.baseColorTextureBase64) {
  2315. var glTFBaseColorTexture = _this._getTextureInfoFromBase64(metallicRoughnessFactors.baseColorTextureBase64, "bjsBaseColorTexture_" + (textures.length) + ".png", mimeType, babylonPBRMaterial.albedoTexture ? babylonPBRMaterial.albedoTexture.coordinatesIndex : null, samplerIndex);
  2316. if (glTFBaseColorTexture) {
  2317. glTFPbrMetallicRoughness.baseColorTexture = glTFBaseColorTexture;
  2318. }
  2319. }
  2320. if (metallicRoughnessFactors.metallicRoughnessTextureBase64) {
  2321. var glTFMRColorTexture = _this._getTextureInfoFromBase64(metallicRoughnessFactors.metallicRoughnessTextureBase64, "bjsMetallicRoughnessTexture_" + (textures.length) + ".png", mimeType, babylonPBRMaterial.reflectivityTexture ? babylonPBRMaterial.reflectivityTexture.coordinatesIndex : null, samplerIndex);
  2322. if (glTFMRColorTexture) {
  2323. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFMRColorTexture;
  2324. }
  2325. }
  2326. return metallicRoughnessFactors;
  2327. });
  2328. }
  2329. else {
  2330. return _this._convertSpecularGlossinessToMetallicRoughness(specGloss);
  2331. }
  2332. });
  2333. };
  2334. /**
  2335. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material
  2336. * @param babylonPBRMaterial BJS PBR Metallic Roughness Material
  2337. * @param mimeType mime type to use for the textures
  2338. * @param images array of glTF image interfaces
  2339. * @param textures array of glTF texture interfaces
  2340. * @param materials array of glTF material interfaces
  2341. * @param imageData map of image file name to data
  2342. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  2343. */
  2344. _GLTFMaterialExporter.prototype._convertPBRMaterialAsync = function (babylonPBRMaterial, mimeType, hasTextureCoords) {
  2345. var _this = this;
  2346. var glTFPbrMetallicRoughness = {};
  2347. var glTFMaterial = {
  2348. name: babylonPBRMaterial.name
  2349. };
  2350. var useMetallicRoughness = babylonPBRMaterial.isMetallicWorkflow();
  2351. if (useMetallicRoughness) {
  2352. if (babylonPBRMaterial.albedoColor) {
  2353. glTFPbrMetallicRoughness.baseColorFactor = [
  2354. babylonPBRMaterial.albedoColor.r,
  2355. babylonPBRMaterial.albedoColor.g,
  2356. babylonPBRMaterial.albedoColor.b,
  2357. babylonPBRMaterial.alpha
  2358. ];
  2359. }
  2360. return this._convertMetalRoughFactorsToMetallicRoughnessAsync(babylonPBRMaterial, mimeType, glTFPbrMetallicRoughness, hasTextureCoords).then(function (metallicRoughness) {
  2361. return _this.setMetallicRoughnessPbrMaterial(metallicRoughness, babylonPBRMaterial, glTFMaterial, glTFPbrMetallicRoughness, mimeType, hasTextureCoords);
  2362. });
  2363. }
  2364. else {
  2365. return this._convertSpecGlossFactorsToMetallicRoughnessAsync(babylonPBRMaterial, mimeType, glTFPbrMetallicRoughness, hasTextureCoords).then(function (metallicRoughness) {
  2366. return _this.setMetallicRoughnessPbrMaterial(metallicRoughness, babylonPBRMaterial, glTFMaterial, glTFPbrMetallicRoughness, mimeType, hasTextureCoords);
  2367. });
  2368. }
  2369. };
  2370. _GLTFMaterialExporter.prototype.setMetallicRoughnessPbrMaterial = function (metallicRoughness, babylonPBRMaterial, glTFMaterial, glTFPbrMetallicRoughness, mimeType, hasTextureCoords) {
  2371. var materialMap = this._exporter._materialMap;
  2372. var materials = this._exporter._materials;
  2373. var promises = [];
  2374. if (metallicRoughness) {
  2375. var alphaMode = null;
  2376. if (babylonPBRMaterial.transparencyMode != null) {
  2377. alphaMode = this._getAlphaMode(babylonPBRMaterial);
  2378. if (alphaMode) {
  2379. if (alphaMode !== "OPAQUE" /* OPAQUE */) { //glTF defaults to opaque
  2380. glTFMaterial.alphaMode = alphaMode;
  2381. if (alphaMode === "MASK" /* MASK */) {
  2382. glTFMaterial.alphaCutoff = babylonPBRMaterial.alphaCutOff;
  2383. }
  2384. }
  2385. }
  2386. }
  2387. if (!(_GLTFMaterialExporter.FuzzyEquals(metallicRoughness.baseColor, BABYLON.Color3.White(), _GLTFMaterialExporter._Epsilon) && babylonPBRMaterial.alpha >= _GLTFMaterialExporter._Epsilon)) {
  2388. glTFPbrMetallicRoughness.baseColorFactor = [
  2389. metallicRoughness.baseColor.r,
  2390. metallicRoughness.baseColor.g,
  2391. metallicRoughness.baseColor.b,
  2392. babylonPBRMaterial.alpha
  2393. ];
  2394. }
  2395. if (metallicRoughness.metallic != null && metallicRoughness.metallic !== 1) {
  2396. glTFPbrMetallicRoughness.metallicFactor = metallicRoughness.metallic;
  2397. }
  2398. if (metallicRoughness.roughness != null && metallicRoughness.roughness !== 1) {
  2399. glTFPbrMetallicRoughness.roughnessFactor = metallicRoughness.roughness;
  2400. }
  2401. if (babylonPBRMaterial.backFaceCulling != null && !babylonPBRMaterial.backFaceCulling) {
  2402. if (!babylonPBRMaterial.twoSidedLighting) {
  2403. BABYLON.Tools.Warn(babylonPBRMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  2404. }
  2405. glTFMaterial.doubleSided = true;
  2406. }
  2407. if (hasTextureCoords) {
  2408. if (babylonPBRMaterial.bumpTexture) {
  2409. var promise = this._exportTextureAsync(babylonPBRMaterial.bumpTexture, mimeType).then(function (glTFTexture) {
  2410. if (glTFTexture) {
  2411. glTFMaterial.normalTexture = glTFTexture;
  2412. if (babylonPBRMaterial.bumpTexture.level !== 1) {
  2413. glTFMaterial.normalTexture.scale = babylonPBRMaterial.bumpTexture.level;
  2414. }
  2415. }
  2416. });
  2417. promises.push(promise);
  2418. }
  2419. if (babylonPBRMaterial.ambientTexture) {
  2420. var promise = this._exportTextureAsync(babylonPBRMaterial.ambientTexture, mimeType).then(function (glTFTexture) {
  2421. if (glTFTexture) {
  2422. var occlusionTexture = {
  2423. index: glTFTexture.index
  2424. };
  2425. glTFMaterial.occlusionTexture = occlusionTexture;
  2426. if (babylonPBRMaterial.ambientTextureStrength) {
  2427. occlusionTexture.strength = babylonPBRMaterial.ambientTextureStrength;
  2428. }
  2429. }
  2430. });
  2431. promises.push(promise);
  2432. }
  2433. if (babylonPBRMaterial.emissiveTexture) {
  2434. var promise = this._exportTextureAsync(babylonPBRMaterial.emissiveTexture, mimeType).then(function (glTFTexture) {
  2435. if (glTFTexture) {
  2436. glTFMaterial.emissiveTexture = glTFTexture;
  2437. }
  2438. });
  2439. promises.push(promise);
  2440. }
  2441. }
  2442. if (!_GLTFMaterialExporter.FuzzyEquals(babylonPBRMaterial.emissiveColor, BABYLON.Color3.Black(), _GLTFMaterialExporter._Epsilon)) {
  2443. glTFMaterial.emissiveFactor = babylonPBRMaterial.emissiveColor.asArray();
  2444. }
  2445. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  2446. materials.push(glTFMaterial);
  2447. materialMap[babylonPBRMaterial.uniqueId] = materials.length - 1;
  2448. }
  2449. return Promise.all(promises).then(function (result) { });
  2450. };
  2451. _GLTFMaterialExporter.prototype.getPixelsFromTexture = function (babylonTexture) {
  2452. var pixels = babylonTexture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT ? babylonTexture.readPixels() : babylonTexture.readPixels();
  2453. return pixels;
  2454. };
  2455. /**
  2456. * Extracts a texture from a Babylon texture into file data and glTF data
  2457. * @param babylonTexture Babylon texture to extract
  2458. * @param mimeType Mime Type of the babylonTexture
  2459. * @return glTF texture info, or null if the texture format is not supported
  2460. */
  2461. _GLTFMaterialExporter.prototype._exportTextureAsync = function (babylonTexture, mimeType) {
  2462. var _this = this;
  2463. var extensionPromise = this._exporter._extensionsPreExportTextureAsync("exporter", babylonTexture, mimeType);
  2464. if (!extensionPromise) {
  2465. return this._exportTextureInfoAsync(babylonTexture, mimeType);
  2466. }
  2467. return extensionPromise.then(function (texture) {
  2468. if (!texture) {
  2469. return _this._exportTextureInfoAsync(babylonTexture, mimeType);
  2470. }
  2471. return _this._exportTextureInfoAsync(texture, mimeType);
  2472. });
  2473. };
  2474. _GLTFMaterialExporter.prototype._exportTextureInfoAsync = function (babylonTexture, mimeType) {
  2475. var _this = this;
  2476. return Promise.resolve().then(function () {
  2477. var textureUid = babylonTexture.uid;
  2478. if (textureUid in _this._textureMap) {
  2479. return _this._textureMap[textureUid];
  2480. }
  2481. else {
  2482. var samplers = _this._exporter._samplers;
  2483. var sampler = _this._getGLTFTextureSampler(babylonTexture);
  2484. var samplerIndex_1 = null;
  2485. // if a pre-existing sampler with identical parameters exists, then reuse the previous sampler
  2486. var foundSamplerIndex = null;
  2487. for (var i = 0; i < samplers.length; ++i) {
  2488. var s = samplers[i];
  2489. if (s.minFilter === sampler.minFilter && s.magFilter === sampler.magFilter &&
  2490. s.wrapS === sampler.wrapS && s.wrapT === sampler.wrapT) {
  2491. foundSamplerIndex = i;
  2492. break;
  2493. }
  2494. }
  2495. if (foundSamplerIndex == null) {
  2496. samplers.push(sampler);
  2497. samplerIndex_1 = samplers.length - 1;
  2498. }
  2499. else {
  2500. samplerIndex_1 = foundSamplerIndex;
  2501. }
  2502. var pixels = _this.getPixelsFromTexture(babylonTexture);
  2503. var size = babylonTexture.getSize();
  2504. return _this._createBase64FromCanvasAsync(pixels, size.width, size.height, mimeType).then(function (base64Data) {
  2505. var textureInfo = _this._getTextureInfoFromBase64(base64Data, babylonTexture.name.replace(/\.\/|\/|\.\\|\\/g, "_"), mimeType, babylonTexture.coordinatesIndex, samplerIndex_1);
  2506. if (textureInfo) {
  2507. _this._textureMap[textureUid] = textureInfo;
  2508. }
  2509. return textureInfo;
  2510. });
  2511. }
  2512. });
  2513. };
  2514. /**
  2515. * Builds a texture from base64 string
  2516. * @param base64Texture base64 texture string
  2517. * @param baseTextureName Name to use for the texture
  2518. * @param mimeType image mime type for the texture
  2519. * @param images array of images
  2520. * @param textures array of textures
  2521. * @param imageData map of image data
  2522. * @returns glTF texture info, or null if the texture format is not supported
  2523. */
  2524. _GLTFMaterialExporter.prototype._getTextureInfoFromBase64 = function (base64Texture, baseTextureName, mimeType, texCoordIndex, samplerIndex) {
  2525. var textures = this._exporter._textures;
  2526. var images = this._exporter._images;
  2527. var imageData = this._exporter._imageData;
  2528. var textureInfo = null;
  2529. var glTFTexture = {
  2530. source: images.length,
  2531. name: baseTextureName
  2532. };
  2533. if (samplerIndex != null) {
  2534. glTFTexture.sampler = samplerIndex;
  2535. }
  2536. var binStr = atob(base64Texture.split(',')[1]);
  2537. var arrBuff = new ArrayBuffer(binStr.length);
  2538. var arr = new Uint8Array(arrBuff);
  2539. for (var i = 0, length_2 = binStr.length; i < length_2; ++i) {
  2540. arr[i] = binStr.charCodeAt(i);
  2541. }
  2542. var imageValues = { data: arr, mimeType: mimeType };
  2543. var extension = mimeType === "image/jpeg" /* JPEG */ ? '.jpeg' : '.png';
  2544. var textureName = baseTextureName + extension;
  2545. if (textureName in imageData) {
  2546. textureName = baseTextureName + "_" + BABYLON.Tools.RandomId() + extension;
  2547. }
  2548. imageData[textureName] = imageValues;
  2549. if (mimeType === "image/jpeg" /* JPEG */ || mimeType === "image/png" /* PNG */) {
  2550. var glTFImage = {
  2551. name: baseTextureName,
  2552. uri: textureName
  2553. };
  2554. var foundIndex = null;
  2555. for (var i = 0; i < images.length; ++i) {
  2556. if (images[i].uri === textureName) {
  2557. foundIndex = i;
  2558. break;
  2559. }
  2560. }
  2561. if (foundIndex == null) {
  2562. images.push(glTFImage);
  2563. glTFTexture.source = images.length - 1;
  2564. }
  2565. else {
  2566. glTFTexture.source = foundIndex;
  2567. }
  2568. textures.push(glTFTexture);
  2569. textureInfo = {
  2570. index: textures.length - 1
  2571. };
  2572. if (texCoordIndex != null) {
  2573. textureInfo.texCoord = texCoordIndex;
  2574. }
  2575. }
  2576. else {
  2577. BABYLON.Tools.Error("Unsupported texture mime type " + mimeType);
  2578. }
  2579. return textureInfo;
  2580. };
  2581. /**
  2582. * Represents the dielectric specular values for R, G and B
  2583. */
  2584. _GLTFMaterialExporter._DielectricSpecular = new BABYLON.Color3(0.04, 0.04, 0.04);
  2585. /**
  2586. * Allows the maximum specular power to be defined for material calculations
  2587. */
  2588. _GLTFMaterialExporter._MaxSpecularPower = 1024;
  2589. /**
  2590. * Numeric tolerance value
  2591. */
  2592. _GLTFMaterialExporter._Epsilon = 1e-6;
  2593. return _GLTFMaterialExporter;
  2594. }());
  2595. Exporter._GLTFMaterialExporter = _GLTFMaterialExporter;
  2596. })(Exporter = GLTF2.Exporter || (GLTF2.Exporter = {}));
  2597. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2598. })(BABYLON || (BABYLON = {}));
  2599. //# sourceMappingURL=babylon.glTFMaterialExporter.js.map
  2600. /// <reference path="../../../../dist/preview release/glTF2Interface/babylon.glTF2Interface.d.ts"/>
  2601. var BABYLON;
  2602. (function (BABYLON) {
  2603. var GLTF2;
  2604. (function (GLTF2) {
  2605. var Exporter;
  2606. (function (Exporter) {
  2607. /**
  2608. * @hidden
  2609. * Enum for handling in tangent and out tangent.
  2610. */
  2611. var _TangentType;
  2612. (function (_TangentType) {
  2613. /**
  2614. * Specifies that input tangents are used.
  2615. */
  2616. _TangentType[_TangentType["INTANGENT"] = 0] = "INTANGENT";
  2617. /**
  2618. * Specifies that output tangents are used.
  2619. */
  2620. _TangentType[_TangentType["OUTTANGENT"] = 1] = "OUTTANGENT";
  2621. })(_TangentType || (_TangentType = {}));
  2622. /**
  2623. * @hidden
  2624. * Utility class for generating glTF animation data from BabylonJS.
  2625. */
  2626. var _GLTFAnimation = /** @class */ (function () {
  2627. function _GLTFAnimation() {
  2628. }
  2629. /**
  2630. * @ignore
  2631. *
  2632. * Creates glTF channel animation from BabylonJS animation.
  2633. * @param babylonTransformNode - BabylonJS mesh.
  2634. * @param animation - animation.
  2635. * @param animationChannelTargetPath - The target animation channel.
  2636. * @param convertToRightHandedSystem - Specifies if the values should be converted to right-handed.
  2637. * @param useQuaternion - Specifies if quaternions are used.
  2638. * @returns nullable IAnimationData
  2639. */
  2640. _GLTFAnimation._CreateNodeAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion, animationSampleRate) {
  2641. var inputs = [];
  2642. var outputs = [];
  2643. var keyFrames = animation.getKeys();
  2644. var minMaxKeyFrames = _GLTFAnimation.calculateMinMaxKeyFrames(keyFrames);
  2645. var interpolationOrBake = _GLTFAnimation._DeduceInterpolation(keyFrames, animationChannelTargetPath, useQuaternion);
  2646. var frameDelta = minMaxKeyFrames.max - minMaxKeyFrames.min;
  2647. var interpolation = interpolationOrBake.interpolationType;
  2648. var shouldBakeAnimation = interpolationOrBake.shouldBakeAnimation;
  2649. if (shouldBakeAnimation) {
  2650. _GLTFAnimation._CreateBakedAnimation(babylonTransformNode, animation, animationChannelTargetPath, minMaxKeyFrames.min, minMaxKeyFrames.max, animation.framePerSecond, animationSampleRate, inputs, outputs, minMaxKeyFrames, convertToRightHandedSystem, useQuaternion);
  2651. }
  2652. else {
  2653. if (interpolation === "LINEAR" /* LINEAR */ || interpolation === "STEP" /* STEP */) {
  2654. _GLTFAnimation._CreateLinearOrStepAnimation(babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion);
  2655. }
  2656. else if (interpolation === "CUBICSPLINE" /* CUBICSPLINE */) {
  2657. _GLTFAnimation._CreateCubicSplineAnimation(babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion);
  2658. }
  2659. else {
  2660. _GLTFAnimation._CreateBakedAnimation(babylonTransformNode, animation, animationChannelTargetPath, minMaxKeyFrames.min, minMaxKeyFrames.max, animation.framePerSecond, animationSampleRate, inputs, outputs, minMaxKeyFrames, convertToRightHandedSystem, useQuaternion);
  2661. }
  2662. }
  2663. if (inputs.length && outputs.length) {
  2664. var result = {
  2665. inputs: inputs,
  2666. outputs: outputs,
  2667. samplerInterpolation: interpolation,
  2668. inputsMin: shouldBakeAnimation ? minMaxKeyFrames.min : BABYLON.Tools.FloatRound(minMaxKeyFrames.min / animation.framePerSecond),
  2669. inputsMax: shouldBakeAnimation ? minMaxKeyFrames.max : BABYLON.Tools.FloatRound(minMaxKeyFrames.max / animation.framePerSecond)
  2670. };
  2671. return result;
  2672. }
  2673. return null;
  2674. };
  2675. _GLTFAnimation._DeduceAnimationInfo = function (animation) {
  2676. var animationChannelTargetPath = null;
  2677. var dataAccessorType = "VEC3" /* VEC3 */;
  2678. var useQuaternion = false;
  2679. var property = animation.targetProperty.split('.');
  2680. switch (property[0]) {
  2681. case 'scaling': {
  2682. animationChannelTargetPath = "scale" /* SCALE */;
  2683. break;
  2684. }
  2685. case 'position': {
  2686. animationChannelTargetPath = "translation" /* TRANSLATION */;
  2687. break;
  2688. }
  2689. case 'rotation': {
  2690. dataAccessorType = "VEC4" /* VEC4 */;
  2691. animationChannelTargetPath = "rotation" /* ROTATION */;
  2692. break;
  2693. }
  2694. case 'rotationQuaternion': {
  2695. dataAccessorType = "VEC4" /* VEC4 */;
  2696. useQuaternion = true;
  2697. animationChannelTargetPath = "rotation" /* ROTATION */;
  2698. break;
  2699. }
  2700. default: {
  2701. BABYLON.Tools.Error("Unsupported animatable property " + property[0]);
  2702. }
  2703. }
  2704. if (animationChannelTargetPath) {
  2705. return { animationChannelTargetPath: animationChannelTargetPath, dataAccessorType: dataAccessorType, useQuaternion: useQuaternion };
  2706. }
  2707. else {
  2708. BABYLON.Tools.Error('animation channel target path and data accessor type could be deduced');
  2709. }
  2710. return null;
  2711. };
  2712. /**
  2713. * @ignore
  2714. * Create node animations from the transform node animations
  2715. * @param babylonTransformNode
  2716. * @param runtimeGLTFAnimation
  2717. * @param idleGLTFAnimations
  2718. * @param nodeMap
  2719. * @param nodes
  2720. * @param binaryWriter
  2721. * @param bufferViews
  2722. * @param accessors
  2723. * @param convertToRightHandedSystem
  2724. */
  2725. _GLTFAnimation._CreateNodeAnimationFromTransformNodeAnimations = function (babylonTransformNode, runtimeGLTFAnimation, idleGLTFAnimations, nodeMap, nodes, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationSampleRate) {
  2726. var glTFAnimation;
  2727. if (babylonTransformNode.animations) {
  2728. for (var _i = 0, _a = babylonTransformNode.animations; _i < _a.length; _i++) {
  2729. var animation = _a[_i];
  2730. var animationInfo = _GLTFAnimation._DeduceAnimationInfo(animation);
  2731. if (animationInfo) {
  2732. glTFAnimation = {
  2733. name: animation.name,
  2734. samplers: [],
  2735. channels: []
  2736. };
  2737. _GLTFAnimation.AddAnimation("" + animation.name, animation.hasRunningRuntimeAnimations ? runtimeGLTFAnimation : glTFAnimation, babylonTransformNode, animation, animationInfo.dataAccessorType, animationInfo.animationChannelTargetPath, nodeMap, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationInfo.useQuaternion, animationSampleRate);
  2738. if (glTFAnimation.samplers.length && glTFAnimation.channels.length) {
  2739. idleGLTFAnimations.push(glTFAnimation);
  2740. }
  2741. }
  2742. }
  2743. ;
  2744. }
  2745. };
  2746. /**
  2747. * @ignore
  2748. * Create node animations from the animation groups
  2749. * @param babylonScene
  2750. * @param glTFAnimations
  2751. * @param nodeMap
  2752. * @param nodes
  2753. * @param binaryWriter
  2754. * @param bufferViews
  2755. * @param accessors
  2756. * @param convertToRightHandedSystem
  2757. */
  2758. _GLTFAnimation._CreateNodeAnimationFromAnimationGroups = function (babylonScene, glTFAnimations, nodeMap, nodes, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationSampleRate) {
  2759. var glTFAnimation;
  2760. if (babylonScene.animationGroups) {
  2761. var animationGroups = babylonScene.animationGroups;
  2762. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  2763. var animationGroup = animationGroups_1[_i];
  2764. glTFAnimation = {
  2765. name: animationGroup.name,
  2766. channels: [],
  2767. samplers: []
  2768. };
  2769. for (var _a = 0, _b = animationGroup.targetedAnimations; _a < _b.length; _a++) {
  2770. var targetAnimation = _b[_a];
  2771. var target = targetAnimation.target;
  2772. var animation = targetAnimation.animation;
  2773. if (target instanceof BABYLON.Mesh || target.length === 1 && target[0] instanceof BABYLON.Mesh) { // TODO: Update to support bones
  2774. var animationInfo = _GLTFAnimation._DeduceAnimationInfo(targetAnimation.animation);
  2775. if (animationInfo) {
  2776. var babylonMesh = target instanceof BABYLON.Mesh ? target : target[0];
  2777. _GLTFAnimation.AddAnimation("" + animation.name, glTFAnimation, babylonMesh, animation, animationInfo.dataAccessorType, animationInfo.animationChannelTargetPath, nodeMap, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationInfo.useQuaternion, animationSampleRate);
  2778. }
  2779. }
  2780. }
  2781. ;
  2782. if (glTFAnimation.channels.length && glTFAnimation.samplers.length) {
  2783. glTFAnimations.push(glTFAnimation);
  2784. }
  2785. }
  2786. ;
  2787. }
  2788. };
  2789. _GLTFAnimation.AddAnimation = function (name, glTFAnimation, babylonTransformNode, animation, dataAccessorType, animationChannelTargetPath, nodeMap, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, useQuaternion, animationSampleRate) {
  2790. var animationData = _GLTFAnimation._CreateNodeAnimation(babylonTransformNode, animation, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion, animationSampleRate);
  2791. var bufferView;
  2792. var accessor;
  2793. var keyframeAccessorIndex;
  2794. var dataAccessorIndex;
  2795. var outputLength;
  2796. var animationSampler;
  2797. var animationChannel;
  2798. if (animationData) {
  2799. var nodeIndex = nodeMap[babylonTransformNode.uniqueId];
  2800. // Creates buffer view and accessor for key frames.
  2801. var byteLength = animationData.inputs.length * 4;
  2802. bufferView = Exporter._GLTFUtilities._CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, undefined, name + " keyframe data view");
  2803. bufferViews.push(bufferView);
  2804. animationData.inputs.forEach(function (input) {
  2805. binaryWriter.setFloat32(input);
  2806. });
  2807. accessor = Exporter._GLTFUtilities._CreateAccessor(bufferViews.length - 1, name + " keyframes", "SCALAR" /* SCALAR */, 5126 /* FLOAT */, animationData.inputs.length, null, [animationData.inputsMin], [animationData.inputsMax]);
  2808. accessors.push(accessor);
  2809. keyframeAccessorIndex = accessors.length - 1;
  2810. // create bufferview and accessor for keyed values.
  2811. outputLength = animationData.outputs.length;
  2812. byteLength = dataAccessorType === "VEC3" /* VEC3 */ ? animationData.outputs.length * 12 : animationData.outputs.length * 16;
  2813. // check for in and out tangents
  2814. bufferView = Exporter._GLTFUtilities._CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, undefined, name + " data view");
  2815. bufferViews.push(bufferView);
  2816. animationData.outputs.forEach(function (output) {
  2817. output.forEach(function (entry) {
  2818. binaryWriter.setFloat32(entry);
  2819. });
  2820. });
  2821. accessor = Exporter._GLTFUtilities._CreateAccessor(bufferViews.length - 1, name + " data", dataAccessorType, 5126 /* FLOAT */, outputLength, null, null, null);
  2822. accessors.push(accessor);
  2823. dataAccessorIndex = accessors.length - 1;
  2824. // create sampler
  2825. animationSampler = {
  2826. interpolation: animationData.samplerInterpolation,
  2827. input: keyframeAccessorIndex,
  2828. output: dataAccessorIndex
  2829. };
  2830. glTFAnimation.samplers.push(animationSampler);
  2831. // create channel
  2832. animationChannel = {
  2833. sampler: glTFAnimation.samplers.length - 1,
  2834. target: {
  2835. node: nodeIndex,
  2836. path: animationChannelTargetPath
  2837. }
  2838. };
  2839. glTFAnimation.channels.push(animationChannel);
  2840. }
  2841. };
  2842. /**
  2843. * Create a baked animation
  2844. * @param babylonTransformNode BabylonJS mesh
  2845. * @param animation BabylonJS animation corresponding to the BabylonJS mesh
  2846. * @param animationChannelTargetPath animation target channel
  2847. * @param minFrame minimum animation frame
  2848. * @param maxFrame maximum animation frame
  2849. * @param fps frames per second of the animation
  2850. * @param inputs input key frames of the animation
  2851. * @param outputs output key frame data of the animation
  2852. * @param convertToRightHandedSystem converts the values to right-handed
  2853. * @param useQuaternion specifies if quaternions should be used
  2854. */
  2855. _GLTFAnimation._CreateBakedAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, minFrame, maxFrame, fps, sampleRate, inputs, outputs, minMaxFrames, convertToRightHandedSystem, useQuaternion) {
  2856. var value;
  2857. var quaternionCache = BABYLON.Quaternion.Identity();
  2858. var previousTime = null;
  2859. var time;
  2860. var maxUsedFrame = null;
  2861. var currKeyFrame = null;
  2862. var nextKeyFrame = null;
  2863. var prevKeyFrame = null;
  2864. var endFrame = null;
  2865. minMaxFrames.min = BABYLON.Tools.FloatRound(minFrame / fps);
  2866. var keyFrames = animation.getKeys();
  2867. for (var i = 0, length_1 = keyFrames.length; i < length_1; ++i) {
  2868. endFrame = null;
  2869. currKeyFrame = keyFrames[i];
  2870. if (i + 1 < length_1) {
  2871. nextKeyFrame = keyFrames[i + 1];
  2872. if (currKeyFrame.value.equals(nextKeyFrame.value)) {
  2873. if (i === 0) { // set the first frame to itself
  2874. endFrame = currKeyFrame.frame;
  2875. }
  2876. else {
  2877. continue;
  2878. }
  2879. }
  2880. else {
  2881. endFrame = nextKeyFrame.frame;
  2882. }
  2883. }
  2884. else {
  2885. // at the last key frame
  2886. prevKeyFrame = keyFrames[i - 1];
  2887. if (currKeyFrame.value.equals(prevKeyFrame.value)) {
  2888. continue;
  2889. }
  2890. else {
  2891. endFrame = maxFrame;
  2892. }
  2893. }
  2894. if (endFrame) {
  2895. for (var f = currKeyFrame.frame; f <= endFrame; f += sampleRate) {
  2896. time = BABYLON.Tools.FloatRound(f / fps);
  2897. if (time === previousTime) {
  2898. continue;
  2899. }
  2900. previousTime = time;
  2901. maxUsedFrame = time;
  2902. value = animation._interpolate(f, 0, undefined, animation.loopMode);
  2903. _GLTFAnimation._SetInterpolatedValue(babylonTransformNode, value, time, animation, animationChannelTargetPath, quaternionCache, inputs, outputs, convertToRightHandedSystem, useQuaternion);
  2904. }
  2905. }
  2906. }
  2907. if (maxUsedFrame) {
  2908. minMaxFrames.max = maxUsedFrame;
  2909. }
  2910. };
  2911. _GLTFAnimation._ConvertFactorToVector3OrQuaternion = function (factor, babylonTransformNode, animation, animationType, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion) {
  2912. var property;
  2913. var componentName;
  2914. var value = null;
  2915. var basePositionRotationOrScale = _GLTFAnimation._GetBasePositionRotationOrScale(babylonTransformNode, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion);
  2916. if (animationType === BABYLON.Animation.ANIMATIONTYPE_FLOAT) { // handles single component x, y, z or w component animation by using a base property and animating over a component.
  2917. property = animation.targetProperty.split('.');
  2918. componentName = property ? property[1] : ''; // x, y, or z component
  2919. value = useQuaternion ? BABYLON.Quaternion.FromArray(basePositionRotationOrScale).normalize() : BABYLON.Vector3.FromArray(basePositionRotationOrScale);
  2920. switch (componentName) {
  2921. case 'x': {
  2922. value[componentName] = (convertToRightHandedSystem && useQuaternion && (animationChannelTargetPath !== "scale" /* SCALE */)) ? -factor : factor;
  2923. break;
  2924. }
  2925. case 'y': {
  2926. value[componentName] = (convertToRightHandedSystem && useQuaternion && (animationChannelTargetPath !== "scale" /* SCALE */)) ? -factor : factor;
  2927. break;
  2928. }
  2929. case 'z': {
  2930. value[componentName] = (convertToRightHandedSystem && !useQuaternion && (animationChannelTargetPath !== "scale" /* SCALE */)) ? -factor : factor;
  2931. break;
  2932. }
  2933. case 'w': {
  2934. value.w = factor;
  2935. break;
  2936. }
  2937. default: {
  2938. BABYLON.Tools.Error("glTFAnimation: Unsupported component type \"" + componentName + "\" for scale animation!");
  2939. }
  2940. }
  2941. }
  2942. return value;
  2943. };
  2944. _GLTFAnimation._SetInterpolatedValue = function (babylonTransformNode, value, time, animation, animationChannelTargetPath, quaternionCache, inputs, outputs, convertToRightHandedSystem, useQuaternion) {
  2945. var animationType = animation.dataType;
  2946. var cacheValue;
  2947. inputs.push(time);
  2948. if (typeof value === "number") {
  2949. value = this._ConvertFactorToVector3OrQuaternion(value, babylonTransformNode, animation, animationType, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion);
  2950. }
  2951. if (value) {
  2952. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  2953. if (useQuaternion) {
  2954. quaternionCache = value;
  2955. }
  2956. else {
  2957. cacheValue = value;
  2958. BABYLON.Quaternion.RotationYawPitchRollToRef(cacheValue.y, cacheValue.x, cacheValue.z, quaternionCache);
  2959. }
  2960. if (convertToRightHandedSystem) {
  2961. Exporter._GLTFUtilities._GetRightHandedQuaternionFromRef(quaternionCache);
  2962. if (!babylonTransformNode.parent) {
  2963. quaternionCache = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(quaternionCache);
  2964. }
  2965. }
  2966. outputs.push(quaternionCache.asArray());
  2967. }
  2968. else {
  2969. cacheValue = value;
  2970. if (convertToRightHandedSystem && (animationChannelTargetPath !== "scale" /* SCALE */)) {
  2971. Exporter._GLTFUtilities._GetRightHandedPositionVector3FromRef(cacheValue);
  2972. if (!babylonTransformNode.parent) {
  2973. cacheValue.x *= -1;
  2974. cacheValue.z *= -1;
  2975. }
  2976. }
  2977. outputs.push(cacheValue.asArray());
  2978. }
  2979. }
  2980. };
  2981. /**
  2982. * Creates linear animation from the animation key frames
  2983. * @param babylonTransformNode BabylonJS mesh
  2984. * @param animation BabylonJS animation
  2985. * @param animationChannelTargetPath The target animation channel
  2986. * @param frameDelta The difference between the last and first frame of the animation
  2987. * @param inputs Array to store the key frame times
  2988. * @param outputs Array to store the key frame data
  2989. * @param convertToRightHandedSystem Specifies if the position data should be converted to right handed
  2990. * @param useQuaternion Specifies if quaternions are used in the animation
  2991. */
  2992. _GLTFAnimation._CreateLinearOrStepAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion) {
  2993. for (var _i = 0, _a = animation.getKeys(); _i < _a.length; _i++) {
  2994. var keyFrame = _a[_i];
  2995. inputs.push(keyFrame.frame / animation.framePerSecond); // keyframes in seconds.
  2996. _GLTFAnimation._AddKeyframeValue(keyFrame, animation, outputs, animationChannelTargetPath, babylonTransformNode, convertToRightHandedSystem, useQuaternion);
  2997. }
  2998. ;
  2999. };
  3000. /**
  3001. * Creates cubic spline animation from the animation key frames
  3002. * @param babylonTransformNode BabylonJS mesh
  3003. * @param animation BabylonJS animation
  3004. * @param animationChannelTargetPath The target animation channel
  3005. * @param frameDelta The difference between the last and first frame of the animation
  3006. * @param inputs Array to store the key frame times
  3007. * @param outputs Array to store the key frame data
  3008. * @param convertToRightHandedSystem Specifies if the position data should be converted to right handed
  3009. * @param useQuaternion Specifies if quaternions are used in the animation
  3010. */
  3011. _GLTFAnimation._CreateCubicSplineAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion) {
  3012. animation.getKeys().forEach(function (keyFrame) {
  3013. inputs.push(keyFrame.frame / animation.framePerSecond); // keyframes in seconds.
  3014. _GLTFAnimation.AddSplineTangent(babylonTransformNode, _TangentType.INTANGENT, outputs, animationChannelTargetPath, "CUBICSPLINE" /* CUBICSPLINE */, keyFrame, frameDelta, useQuaternion, convertToRightHandedSystem);
  3015. _GLTFAnimation._AddKeyframeValue(keyFrame, animation, outputs, animationChannelTargetPath, babylonTransformNode, convertToRightHandedSystem, useQuaternion);
  3016. _GLTFAnimation.AddSplineTangent(babylonTransformNode, _TangentType.OUTTANGENT, outputs, animationChannelTargetPath, "CUBICSPLINE" /* CUBICSPLINE */, keyFrame, frameDelta, useQuaternion, convertToRightHandedSystem);
  3017. });
  3018. };
  3019. _GLTFAnimation._GetBasePositionRotationOrScale = function (babylonTransformNode, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion) {
  3020. var basePositionRotationOrScale;
  3021. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  3022. if (useQuaternion) {
  3023. if (babylonTransformNode.rotationQuaternion) {
  3024. basePositionRotationOrScale = babylonTransformNode.rotationQuaternion.asArray();
  3025. if (convertToRightHandedSystem) {
  3026. Exporter._GLTFUtilities._GetRightHandedQuaternionArrayFromRef(basePositionRotationOrScale);
  3027. if (!babylonTransformNode.parent) {
  3028. basePositionRotationOrScale = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(BABYLON.Quaternion.FromArray(basePositionRotationOrScale)).asArray();
  3029. }
  3030. }
  3031. }
  3032. else {
  3033. basePositionRotationOrScale = BABYLON.Quaternion.Identity().asArray();
  3034. }
  3035. }
  3036. else {
  3037. basePositionRotationOrScale = babylonTransformNode.rotation.asArray();
  3038. Exporter._GLTFUtilities._GetRightHandedNormalArray3FromRef(basePositionRotationOrScale);
  3039. }
  3040. }
  3041. else if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  3042. basePositionRotationOrScale = babylonTransformNode.position.asArray();
  3043. if (convertToRightHandedSystem) {
  3044. Exporter._GLTFUtilities._GetRightHandedPositionArray3FromRef(basePositionRotationOrScale);
  3045. }
  3046. }
  3047. else { // scale
  3048. basePositionRotationOrScale = babylonTransformNode.scaling.asArray();
  3049. }
  3050. return basePositionRotationOrScale;
  3051. };
  3052. /**
  3053. * Adds a key frame value
  3054. * @param keyFrame
  3055. * @param animation
  3056. * @param outputs
  3057. * @param animationChannelTargetPath
  3058. * @param basePositionRotationOrScale
  3059. * @param convertToRightHandedSystem
  3060. * @param useQuaternion
  3061. */
  3062. _GLTFAnimation._AddKeyframeValue = function (keyFrame, animation, outputs, animationChannelTargetPath, babylonTransformNode, convertToRightHandedSystem, useQuaternion) {
  3063. var value;
  3064. var newPositionRotationOrScale;
  3065. var animationType = animation.dataType;
  3066. if (animationType === BABYLON.Animation.ANIMATIONTYPE_VECTOR3) {
  3067. value = keyFrame.value.asArray();
  3068. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  3069. var array = BABYLON.Vector3.FromArray(value);
  3070. var rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(array.y, array.x, array.z);
  3071. if (convertToRightHandedSystem) {
  3072. Exporter._GLTFUtilities._GetRightHandedQuaternionFromRef(rotationQuaternion);
  3073. if (!babylonTransformNode.parent) {
  3074. rotationQuaternion = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(rotationQuaternion);
  3075. }
  3076. }
  3077. value = rotationQuaternion.asArray();
  3078. }
  3079. else if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  3080. if (convertToRightHandedSystem) {
  3081. Exporter._GLTFUtilities._GetRightHandedNormalArray3FromRef(value);
  3082. if (!babylonTransformNode.parent) {
  3083. value[0] *= -1;
  3084. value[2] *= -1;
  3085. }
  3086. }
  3087. }
  3088. outputs.push(value); // scale vector.
  3089. }
  3090. else if (animationType === BABYLON.Animation.ANIMATIONTYPE_FLOAT) { // handles single component x, y, z or w component animation by using a base property and animating over a component.
  3091. newPositionRotationOrScale = this._ConvertFactorToVector3OrQuaternion(keyFrame.value, babylonTransformNode, animation, animationType, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion);
  3092. if (newPositionRotationOrScale) {
  3093. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  3094. var posRotScale = useQuaternion ? newPositionRotationOrScale : BABYLON.Quaternion.RotationYawPitchRoll(newPositionRotationOrScale.y, newPositionRotationOrScale.x, newPositionRotationOrScale.z).normalize();
  3095. if (convertToRightHandedSystem) {
  3096. Exporter._GLTFUtilities._GetRightHandedQuaternionFromRef(posRotScale);
  3097. if (!babylonTransformNode.parent) {
  3098. posRotScale = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(posRotScale);
  3099. }
  3100. }
  3101. outputs.push(posRotScale.asArray());
  3102. }
  3103. else if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  3104. if (convertToRightHandedSystem) {
  3105. Exporter._GLTFUtilities._GetRightHandedNormalVector3FromRef(newPositionRotationOrScale);
  3106. if (!babylonTransformNode.parent) {
  3107. newPositionRotationOrScale.x *= -1;
  3108. newPositionRotationOrScale.z *= -1;
  3109. }
  3110. }
  3111. }
  3112. outputs.push(newPositionRotationOrScale.asArray());
  3113. }
  3114. }
  3115. else if (animationType === BABYLON.Animation.ANIMATIONTYPE_QUATERNION) {
  3116. value = keyFrame.value.normalize().asArray();
  3117. if (convertToRightHandedSystem) {
  3118. Exporter._GLTFUtilities._GetRightHandedQuaternionArrayFromRef(value);
  3119. if (!babylonTransformNode.parent) {
  3120. value = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(BABYLON.Quaternion.FromArray(value)).asArray();
  3121. }
  3122. }
  3123. outputs.push(value);
  3124. }
  3125. else {
  3126. BABYLON.Tools.Error('glTFAnimation: Unsupported key frame values for animation!');
  3127. }
  3128. };
  3129. /**
  3130. * Determine the interpolation based on the key frames
  3131. * @param keyFrames
  3132. * @param animationChannelTargetPath
  3133. * @param useQuaternion
  3134. */
  3135. _GLTFAnimation._DeduceInterpolation = function (keyFrames, animationChannelTargetPath, useQuaternion) {
  3136. var interpolationType;
  3137. var shouldBakeAnimation = false;
  3138. var key;
  3139. if (animationChannelTargetPath === "rotation" /* ROTATION */ && !useQuaternion) {
  3140. return { interpolationType: "LINEAR" /* LINEAR */, shouldBakeAnimation: true };
  3141. }
  3142. for (var i = 0, length_2 = keyFrames.length; i < length_2; ++i) {
  3143. key = keyFrames[i];
  3144. if (key.inTangent || key.outTangent) {
  3145. if (interpolationType) {
  3146. if (interpolationType !== "CUBICSPLINE" /* CUBICSPLINE */) {
  3147. interpolationType = "LINEAR" /* LINEAR */;
  3148. shouldBakeAnimation = true;
  3149. break;
  3150. }
  3151. }
  3152. else {
  3153. interpolationType = "CUBICSPLINE" /* CUBICSPLINE */;
  3154. }
  3155. }
  3156. else {
  3157. if (interpolationType) {
  3158. if (interpolationType === "CUBICSPLINE" /* CUBICSPLINE */ ||
  3159. (key.interpolation && (key.interpolation === BABYLON.AnimationKeyInterpolation.STEP) && interpolationType !== "STEP" /* STEP */)) {
  3160. interpolationType = "LINEAR" /* LINEAR */;
  3161. shouldBakeAnimation = true;
  3162. break;
  3163. }
  3164. }
  3165. else {
  3166. if (key.interpolation && (key.interpolation === BABYLON.AnimationKeyInterpolation.STEP)) {
  3167. interpolationType = "STEP" /* STEP */;
  3168. }
  3169. else {
  3170. interpolationType = "LINEAR" /* LINEAR */;
  3171. }
  3172. }
  3173. }
  3174. }
  3175. if (!interpolationType) {
  3176. interpolationType = "LINEAR" /* LINEAR */;
  3177. }
  3178. return { interpolationType: interpolationType, shouldBakeAnimation: shouldBakeAnimation };
  3179. };
  3180. /**
  3181. * Adds an input tangent or output tangent to the output data
  3182. * If an input tangent or output tangent is missing, it uses the zero vector or zero quaternion
  3183. * @param tangentType Specifies which type of tangent to handle (inTangent or outTangent)
  3184. * @param outputs The animation data by keyframe
  3185. * @param animationChannelTargetPath The target animation channel
  3186. * @param interpolation The interpolation type
  3187. * @param keyFrame The key frame with the animation data
  3188. * @param frameDelta Time difference between two frames used to scale the tangent by the frame delta
  3189. * @param useQuaternion Specifies if quaternions are used
  3190. * @param convertToRightHandedSystem Specifies if the values should be converted to right-handed
  3191. */
  3192. _GLTFAnimation.AddSplineTangent = function (babylonTransformNode, tangentType, outputs, animationChannelTargetPath, interpolation, keyFrame, frameDelta, useQuaternion, convertToRightHandedSystem) {
  3193. var tangent;
  3194. var tangentValue = tangentType === _TangentType.INTANGENT ? keyFrame.inTangent : keyFrame.outTangent;
  3195. if (interpolation === "CUBICSPLINE" /* CUBICSPLINE */) {
  3196. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  3197. if (tangentValue) {
  3198. if (useQuaternion) {
  3199. tangent = tangentValue.scale(frameDelta).asArray();
  3200. }
  3201. else {
  3202. var array = tangentValue.scale(frameDelta);
  3203. tangent = BABYLON.Quaternion.RotationYawPitchRoll(array.y, array.x, array.z).asArray();
  3204. }
  3205. if (convertToRightHandedSystem) {
  3206. Exporter._GLTFUtilities._GetRightHandedQuaternionArrayFromRef(tangent);
  3207. if (!babylonTransformNode.parent) {
  3208. tangent = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(BABYLON.Quaternion.FromArray(tangent)).asArray();
  3209. }
  3210. }
  3211. }
  3212. else {
  3213. tangent = [0, 0, 0, 0];
  3214. }
  3215. }
  3216. else {
  3217. if (tangentValue) {
  3218. tangent = tangentValue.scale(frameDelta).asArray();
  3219. if (convertToRightHandedSystem) {
  3220. if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  3221. Exporter._GLTFUtilities._GetRightHandedPositionArray3FromRef(tangent);
  3222. if (!babylonTransformNode.parent) {
  3223. tangent[0] *= -1; // x
  3224. tangent[2] *= -1; // z
  3225. }
  3226. }
  3227. }
  3228. }
  3229. else {
  3230. tangent = [0, 0, 0];
  3231. }
  3232. }
  3233. outputs.push(tangent);
  3234. }
  3235. };
  3236. /**
  3237. * Get the minimum and maximum key frames' frame values
  3238. * @param keyFrames animation key frames
  3239. * @returns the minimum and maximum key frame value
  3240. */
  3241. _GLTFAnimation.calculateMinMaxKeyFrames = function (keyFrames) {
  3242. var min = Infinity;
  3243. var max = -Infinity;
  3244. keyFrames.forEach(function (keyFrame) {
  3245. min = Math.min(min, keyFrame.frame);
  3246. max = Math.max(max, keyFrame.frame);
  3247. });
  3248. return { min: min, max: max };
  3249. };
  3250. return _GLTFAnimation;
  3251. }());
  3252. Exporter._GLTFAnimation = _GLTFAnimation;
  3253. })(Exporter = GLTF2.Exporter || (GLTF2.Exporter = {}));
  3254. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3255. })(BABYLON || (BABYLON = {}));
  3256. //# sourceMappingURL=babylon.glTFAnimation.js.map
  3257. /// <reference path="../../../../dist/preview release/glTF2Interface/babylon.glTF2Interface.d.ts"/>
  3258. var BABYLON;
  3259. (function (BABYLON) {
  3260. var GLTF2;
  3261. (function (GLTF2) {
  3262. var Exporter;
  3263. (function (Exporter) {
  3264. /**
  3265. * @hidden
  3266. */
  3267. var _GLTFUtilities = /** @class */ (function () {
  3268. function _GLTFUtilities() {
  3269. }
  3270. /**
  3271. * Creates a buffer view based on the supplied arguments
  3272. * @param bufferIndex index value of the specified buffer
  3273. * @param byteOffset byte offset value
  3274. * @param byteLength byte length of the bufferView
  3275. * @param byteStride byte distance between conequential elements
  3276. * @param name name of the buffer view
  3277. * @returns bufferView for glTF
  3278. */
  3279. _GLTFUtilities._CreateBufferView = function (bufferIndex, byteOffset, byteLength, byteStride, name) {
  3280. var bufferview = { buffer: bufferIndex, byteLength: byteLength };
  3281. if (byteOffset) {
  3282. bufferview.byteOffset = byteOffset;
  3283. }
  3284. if (name) {
  3285. bufferview.name = name;
  3286. }
  3287. if (byteStride) {
  3288. bufferview.byteStride = byteStride;
  3289. }
  3290. return bufferview;
  3291. };
  3292. /**
  3293. * Creates an accessor based on the supplied arguments
  3294. * @param bufferviewIndex The index of the bufferview referenced by this accessor
  3295. * @param name The name of the accessor
  3296. * @param type The type of the accessor
  3297. * @param componentType The datatype of components in the attribute
  3298. * @param count The number of attributes referenced by this accessor
  3299. * @param byteOffset The offset relative to the start of the bufferView in bytes
  3300. * @param min Minimum value of each component in this attribute
  3301. * @param max Maximum value of each component in this attribute
  3302. * @returns accessor for glTF
  3303. */
  3304. _GLTFUtilities._CreateAccessor = function (bufferviewIndex, name, type, componentType, count, byteOffset, min, max) {
  3305. var accessor = { name: name, bufferView: bufferviewIndex, componentType: componentType, count: count, type: type };
  3306. if (min != null) {
  3307. accessor.min = min;
  3308. }
  3309. if (max != null) {
  3310. accessor.max = max;
  3311. }
  3312. if (byteOffset != null) {
  3313. accessor.byteOffset = byteOffset;
  3314. }
  3315. return accessor;
  3316. };
  3317. /**
  3318. * Calculates the minimum and maximum values of an array of position floats
  3319. * @param positions Positions array of a mesh
  3320. * @param vertexStart Starting vertex offset to calculate min and max values
  3321. * @param vertexCount Number of vertices to check for min and max values
  3322. * @returns min number array and max number array
  3323. */
  3324. _GLTFUtilities._CalculateMinMaxPositions = function (positions, vertexStart, vertexCount, convertToRightHandedSystem) {
  3325. var min = [Infinity, Infinity, Infinity];
  3326. var max = [-Infinity, -Infinity, -Infinity];
  3327. var positionStrideSize = 3;
  3328. var indexOffset;
  3329. var position;
  3330. var vector;
  3331. if (vertexCount) {
  3332. for (var i = vertexStart, length_1 = vertexStart + vertexCount; i < length_1; ++i) {
  3333. indexOffset = positionStrideSize * i;
  3334. position = BABYLON.Vector3.FromArray(positions, indexOffset);
  3335. if (convertToRightHandedSystem) {
  3336. _GLTFUtilities._GetRightHandedPositionVector3FromRef(position);
  3337. }
  3338. vector = position.asArray();
  3339. for (var j = 0; j < positionStrideSize; ++j) {
  3340. var num = vector[j];
  3341. if (num < min[j]) {
  3342. min[j] = num;
  3343. }
  3344. if (num > max[j]) {
  3345. max[j] = num;
  3346. }
  3347. ++indexOffset;
  3348. }
  3349. }
  3350. }
  3351. return { min: min, max: max };
  3352. };
  3353. /**
  3354. * Converts a new right-handed Vector3
  3355. * @param vector vector3 array
  3356. * @returns right-handed Vector3
  3357. */
  3358. _GLTFUtilities._GetRightHandedPositionVector3 = function (vector) {
  3359. return new BABYLON.Vector3(vector.x, vector.y, -vector.z);
  3360. };
  3361. /**
  3362. * Converts a Vector3 to right-handed
  3363. * @param vector Vector3 to convert to right-handed
  3364. */
  3365. _GLTFUtilities._GetRightHandedPositionVector3FromRef = function (vector) {
  3366. vector.z *= -1;
  3367. };
  3368. /**
  3369. * Converts a three element number array to right-handed
  3370. * @param vector number array to convert to right-handed
  3371. */
  3372. _GLTFUtilities._GetRightHandedPositionArray3FromRef = function (vector) {
  3373. vector[2] *= -1;
  3374. };
  3375. /**
  3376. * Converts a new right-handed Vector3
  3377. * @param vector vector3 array
  3378. * @returns right-handed Vector3
  3379. */
  3380. _GLTFUtilities._GetRightHandedNormalVector3 = function (vector) {
  3381. return new BABYLON.Vector3(vector.x, vector.y, -vector.z);
  3382. };
  3383. /**
  3384. * Converts a Vector3 to right-handed
  3385. * @param vector Vector3 to convert to right-handed
  3386. */
  3387. _GLTFUtilities._GetRightHandedNormalVector3FromRef = function (vector) {
  3388. vector.z *= -1;
  3389. };
  3390. /**
  3391. * Converts a three element number array to right-handed
  3392. * @param vector number array to convert to right-handed
  3393. */
  3394. _GLTFUtilities._GetRightHandedNormalArray3FromRef = function (vector) {
  3395. vector[2] *= -1;
  3396. };
  3397. /**
  3398. * Converts a Vector4 to right-handed
  3399. * @param vector Vector4 to convert to right-handed
  3400. */
  3401. _GLTFUtilities._GetRightHandedVector4FromRef = function (vector) {
  3402. vector.z *= -1;
  3403. vector.w *= -1;
  3404. };
  3405. /**
  3406. * Converts a Vector4 to right-handed
  3407. * @param vector Vector4 to convert to right-handed
  3408. */
  3409. _GLTFUtilities._GetRightHandedArray4FromRef = function (vector) {
  3410. vector[2] *= -1;
  3411. vector[3] *= -1;
  3412. };
  3413. /**
  3414. * Converts a Quaternion to right-handed
  3415. * @param quaternion Source quaternion to convert to right-handed
  3416. */
  3417. _GLTFUtilities._GetRightHandedQuaternionFromRef = function (quaternion) {
  3418. quaternion.x *= -1;
  3419. quaternion.y *= -1;
  3420. };
  3421. /**
  3422. * Converts a Quaternion to right-handed
  3423. * @param quaternion Source quaternion to convert to right-handed
  3424. */
  3425. _GLTFUtilities._GetRightHandedQuaternionArrayFromRef = function (quaternion) {
  3426. quaternion[0] *= -1;
  3427. quaternion[1] *= -1;
  3428. };
  3429. _GLTFUtilities._NormalizeTangentFromRef = function (tangent) {
  3430. var length = Math.sqrt(tangent.x * tangent.x + tangent.y * tangent.y + tangent.z * tangent.z);
  3431. if (length > 0) {
  3432. tangent.x /= length;
  3433. tangent.y /= length;
  3434. tangent.z /= length;
  3435. }
  3436. };
  3437. return _GLTFUtilities;
  3438. }());
  3439. Exporter._GLTFUtilities = _GLTFUtilities;
  3440. })(Exporter = GLTF2.Exporter || (GLTF2.Exporter = {}));
  3441. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3442. })(BABYLON || (BABYLON = {}));
  3443. //# sourceMappingURL=babylon.glTFUtilities.js.map
  3444. /// <reference path="../../../../dist/preview release/gltf2Interface/babylon.glTF2Interface.d.ts"/>
  3445. //# sourceMappingURL=babylon.glTFExporterExtension.js.map
  3446. /// <reference path="../../../dist/preview release/glTF2Interface/babylon.glTF2Interface.d.ts"/>
  3447. //# sourceMappingURL=babylon.glTFFileExporter.js.map
  3448. /// <reference path="../../../../../dist/preview release/gltf2Interface/babylon.glTF2Interface.d.ts"/>
  3449. /**
  3450. * @hidden
  3451. */
  3452. var BABYLON;
  3453. (function (BABYLON) {
  3454. var GLTF2;
  3455. (function (GLTF2) {
  3456. var Exporter;
  3457. (function (Exporter) {
  3458. var Extensions;
  3459. (function (Extensions) {
  3460. var NAME = "KHR_texture_transform";
  3461. /**
  3462. * @hidden
  3463. */
  3464. var KHR_texture_transform = /** @class */ (function () {
  3465. function KHR_texture_transform(exporter) {
  3466. /** Name of this extension */
  3467. this.name = NAME;
  3468. /** Defines whether this extension is enabled */
  3469. this.enabled = true;
  3470. /** Defines whether this extension is required */
  3471. this.required = false;
  3472. this._exporter = exporter;
  3473. }
  3474. KHR_texture_transform.prototype.dispose = function () {
  3475. delete this._exporter;
  3476. };
  3477. KHR_texture_transform.prototype.preExportTextureAsync = function (context, babylonTexture, mimeType) {
  3478. var _this = this;
  3479. return new Promise(function (resolve, reject) {
  3480. var texture_transform_extension = {};
  3481. if (babylonTexture.uOffset !== 0 || babylonTexture.vOffset !== 0) {
  3482. texture_transform_extension.offset = [babylonTexture.uOffset, babylonTexture.vOffset];
  3483. }
  3484. if (babylonTexture.uScale !== 1 || babylonTexture.vScale !== 1) {
  3485. texture_transform_extension.scale = [babylonTexture.uScale, babylonTexture.vScale];
  3486. }
  3487. if (babylonTexture.wAng !== 0) {
  3488. texture_transform_extension.rotation = babylonTexture.wAng;
  3489. }
  3490. if (!Object.keys(texture_transform_extension).length) {
  3491. resolve(babylonTexture);
  3492. }
  3493. var scale = texture_transform_extension.scale ? new BABYLON.Vector2(texture_transform_extension.scale[0], texture_transform_extension.scale[1]) : BABYLON.Vector2.One();
  3494. var rotation = texture_transform_extension.rotation != null ? texture_transform_extension.rotation : 0;
  3495. var offset = texture_transform_extension.offset ? new BABYLON.Vector2(texture_transform_extension.offset[0], texture_transform_extension.offset[1]) : BABYLON.Vector2.Zero();
  3496. var scene = babylonTexture.getScene();
  3497. if (!scene) {
  3498. reject(context + ": \"scene\" is not defined for Babylon texture " + babylonTexture.name + "!");
  3499. }
  3500. else {
  3501. _this.textureTransformTextureAsync(babylonTexture, offset, rotation, scale, scene).then(function (texture) {
  3502. resolve(texture);
  3503. });
  3504. }
  3505. });
  3506. };
  3507. /**
  3508. * Transform the babylon texture by the offset, rotation and scale parameters using a procedural texture
  3509. * @param babylonTexture
  3510. * @param offset
  3511. * @param rotation
  3512. * @param scale
  3513. * @param scene
  3514. */
  3515. KHR_texture_transform.prototype.textureTransformTextureAsync = function (babylonTexture, offset, rotation, scale, scene) {
  3516. return new Promise(function (resolve, reject) {
  3517. var proceduralTexture = new BABYLON.ProceduralTexture("" + babylonTexture.name, babylonTexture.getSize(), "textureTransform", scene);
  3518. if (!proceduralTexture) {
  3519. BABYLON.Tools.Log("Cannot create procedural texture for " + babylonTexture.name + "!");
  3520. resolve(babylonTexture);
  3521. }
  3522. proceduralTexture.setTexture("textureSampler", babylonTexture);
  3523. proceduralTexture.setMatrix("textureTransformMat", babylonTexture.getTextureMatrix());
  3524. // isReady trigger creation of effect if it doesnt exist yet
  3525. if (proceduralTexture.isReady()) {
  3526. proceduralTexture.render();
  3527. resolve(proceduralTexture);
  3528. }
  3529. else {
  3530. proceduralTexture._effect.onCompileObservable.add(function () {
  3531. proceduralTexture.render();
  3532. resolve(proceduralTexture);
  3533. });
  3534. }
  3535. });
  3536. };
  3537. return KHR_texture_transform;
  3538. }());
  3539. Extensions.KHR_texture_transform = KHR_texture_transform;
  3540. Exporter._Exporter.RegisterExtension(NAME, function (exporter) { return new KHR_texture_transform(exporter); });
  3541. })(Extensions = Exporter.Extensions || (Exporter.Extensions = {}));
  3542. })(Exporter = GLTF2.Exporter || (GLTF2.Exporter = {}));
  3543. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3544. })(BABYLON || (BABYLON = {}));
  3545. //# sourceMappingURL=KHR_texture_transform.js.map