babylonjs.serializers.js 195 KB

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