babylonjs.serializers.js 193 KB

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