babylon.glTF2Serializer.js 187 KB

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