babylon.glTF2Serializer.js 185 KB

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