babylon.glTF2Serializer.js 188 KB

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