babylonjs.serializers.js 191 KB

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