babylon.glTF2Serializer.js 186 KB

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