babylonjs.serializers.js 194 KB

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