GLTFExporter.js 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354
  1. import {
  2. BufferAttribute,
  3. BufferGeometry,
  4. ClampToEdgeWrapping,
  5. DoubleSide,
  6. InterpolateDiscrete,
  7. InterpolateLinear,
  8. LinearFilter,
  9. LinearMipmapLinearFilter,
  10. LinearMipmapNearestFilter,
  11. MathUtils,
  12. Matrix4,
  13. MirroredRepeatWrapping,
  14. NearestFilter,
  15. NearestMipmapLinearFilter,
  16. NearestMipmapNearestFilter,
  17. PropertyBinding,
  18. RGBAFormat,
  19. RGBFormat,
  20. RepeatWrapping,
  21. Scene,
  22. Vector3
  23. } from "../../../build/three.module.js";
  24. //------------------------------------------------------------------------------
  25. // Constants
  26. //------------------------------------------------------------------------------
  27. var WEBGL_CONSTANTS = {
  28. POINTS: 0x0000,
  29. LINES: 0x0001,
  30. LINE_LOOP: 0x0002,
  31. LINE_STRIP: 0x0003,
  32. TRIANGLES: 0x0004,
  33. TRIANGLE_STRIP: 0x0005,
  34. TRIANGLE_FAN: 0x0006,
  35. UNSIGNED_BYTE: 0x1401,
  36. UNSIGNED_SHORT: 0x1403,
  37. FLOAT: 0x1406,
  38. UNSIGNED_INT: 0x1405,
  39. ARRAY_BUFFER: 0x8892,
  40. ELEMENT_ARRAY_BUFFER: 0x8893,
  41. NEAREST: 0x2600,
  42. LINEAR: 0x2601,
  43. NEAREST_MIPMAP_NEAREST: 0x2700,
  44. LINEAR_MIPMAP_NEAREST: 0x2701,
  45. NEAREST_MIPMAP_LINEAR: 0x2702,
  46. LINEAR_MIPMAP_LINEAR: 0x2703,
  47. CLAMP_TO_EDGE: 33071,
  48. MIRRORED_REPEAT: 33648,
  49. REPEAT: 10497
  50. };
  51. var identityArray = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ];
  52. var THREE_TO_WEBGL = {};
  53. THREE_TO_WEBGL[ NearestFilter ] = WEBGL_CONSTANTS.NEAREST;
  54. THREE_TO_WEBGL[ NearestMipmapNearestFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST;
  55. THREE_TO_WEBGL[ NearestMipmapLinearFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR;
  56. THREE_TO_WEBGL[ LinearFilter ] = WEBGL_CONSTANTS.LINEAR;
  57. THREE_TO_WEBGL[ LinearMipmapNearestFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST;
  58. THREE_TO_WEBGL[ LinearMipmapLinearFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR;
  59. THREE_TO_WEBGL[ ClampToEdgeWrapping ] = WEBGL_CONSTANTS.CLAMP_TO_EDGE;
  60. THREE_TO_WEBGL[ RepeatWrapping ] = WEBGL_CONSTANTS.REPEAT;
  61. THREE_TO_WEBGL[ MirroredRepeatWrapping ] = WEBGL_CONSTANTS.MIRRORED_REPEAT;
  62. var PATH_PROPERTIES = {
  63. scale: 'scale',
  64. position: 'translation',
  65. quaternion: 'rotation',
  66. morphTargetInfluences: 'weights'
  67. };
  68. //------------------------------------------------------------------------------
  69. // GLTF Exporter
  70. //------------------------------------------------------------------------------
  71. var GLTFExporter = function () {};
  72. GLTFExporter.prototype = {
  73. constructor: GLTFExporter,
  74. /**
  75. * Parse scenes and generate GLTF output
  76. * @param {Scene or [THREE.Scenes]} input Scene or Array of THREE.Scenes
  77. * @param {Function} onDone Callback on completed
  78. * @param {Object} options options
  79. */
  80. parse: function ( input, onDone, options ) {
  81. var DEFAULT_OPTIONS = {
  82. binary: false,
  83. trs: false,
  84. onlyVisible: true,
  85. truncateDrawRange: true,
  86. embedImages: true,
  87. maxTextureSize: Infinity,
  88. animations: [],
  89. includeCustomExtensions: false
  90. };
  91. options = Object.assign( {}, DEFAULT_OPTIONS, options );
  92. if ( options.animations.length > 0 ) {
  93. // Only TRS properties, and not matrices, may be targeted by animation.
  94. options.trs = true;
  95. }
  96. var outputJSON = {
  97. asset: {
  98. version: "2.0",
  99. generator: "GLTFExporter"
  100. }
  101. };
  102. var byteOffset = 0;
  103. var buffers = [];
  104. var pending = [];
  105. var nodeMap = new Map();
  106. var skins = [];
  107. var extensionsUsed = {};
  108. var cachedData = {
  109. meshes: new Map(),
  110. attributes: new Map(),
  111. attributesNormalized: new Map(),
  112. materials: new Map(),
  113. textures: new Map(),
  114. images: new Map()
  115. };
  116. var cachedCanvas;
  117. var uids = new Map();
  118. var uid = 0;
  119. /**
  120. * Assign and return a temporal unique id for an object
  121. * especially which doesn't have .uuid
  122. * @param {Object} object
  123. * @return {Integer}
  124. */
  125. function getUID( object ) {
  126. if ( ! uids.has( object ) ) uids.set( object, uid ++ );
  127. return uids.get( object );
  128. }
  129. /**
  130. * Compare two arrays
  131. * @param {Array} array1 Array 1 to compare
  132. * @param {Array} array2 Array 2 to compare
  133. * @return {Boolean} Returns true if both arrays are equal
  134. */
  135. function equalArray( array1, array2 ) {
  136. return ( array1.length === array2.length ) && array1.every( function ( element, index ) {
  137. return element === array2[ index ];
  138. } );
  139. }
  140. /**
  141. * Is identity matrix
  142. *
  143. * @param {Matrix4} matrix
  144. * @returns {Boolean} Returns true, if parameter is identity matrix
  145. */
  146. function isIdentityMatrix( matrix ) {
  147. return equalArray( matrix.elements, identityArray );
  148. }
  149. /**
  150. * Converts a string to an ArrayBuffer.
  151. * @param {string} text
  152. * @return {ArrayBuffer}
  153. */
  154. function stringToArrayBuffer( text ) {
  155. if ( window.TextEncoder !== undefined ) {
  156. return new TextEncoder().encode( text ).buffer;
  157. }
  158. var array = new Uint8Array( new ArrayBuffer( text.length ) );
  159. for ( var i = 0, il = text.length; i < il; i ++ ) {
  160. var value = text.charCodeAt( i );
  161. // Replacing multi-byte character with space(0x20).
  162. array[ i ] = value > 0xFF ? 0x20 : value;
  163. }
  164. return array.buffer;
  165. }
  166. /**
  167. * Get the min and max vectors from the given attribute
  168. * @param {BufferAttribute} attribute Attribute to find the min/max in range from start to start + count
  169. * @param {Integer} start
  170. * @param {Integer} count
  171. * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
  172. */
  173. function getMinMax( attribute, start, count ) {
  174. var output = {
  175. min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
  176. max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
  177. };
  178. for ( var i = start; i < start + count; i ++ ) {
  179. for ( var a = 0; a < attribute.itemSize; a ++ ) {
  180. var value;
  181. if ( attribute.itemSize > 4 ) {
  182. // no support for interleaved data for itemSize > 4
  183. value = attribute.array[ i * attribute.itemSize + a ];
  184. } else {
  185. if ( a === 0 ) value = attribute.getX( i );
  186. else if ( a === 1 ) value = attribute.getY( i );
  187. else if ( a === 2 ) value = attribute.getZ( i );
  188. else if ( a === 3 ) value = attribute.getW( i );
  189. }
  190. output.min[ a ] = Math.min( output.min[ a ], value );
  191. output.max[ a ] = Math.max( output.max[ a ], value );
  192. }
  193. }
  194. return output;
  195. }
  196. /**
  197. * Checks if normal attribute values are normalized.
  198. *
  199. * @param {BufferAttribute} normal
  200. * @returns {Boolean}
  201. *
  202. */
  203. function isNormalizedNormalAttribute( normal ) {
  204. if ( cachedData.attributesNormalized.has( normal ) ) {
  205. return false;
  206. }
  207. var v = new Vector3();
  208. for ( var i = 0, il = normal.count; i < il; i ++ ) {
  209. // 0.0005 is from glTF-validator
  210. if ( Math.abs( v.fromBufferAttribute( normal, i ).length() - 1.0 ) > 0.0005 ) return false;
  211. }
  212. return true;
  213. }
  214. /**
  215. * Creates normalized normal buffer attribute.
  216. *
  217. * @param {BufferAttribute} normal
  218. * @returns {BufferAttribute}
  219. *
  220. */
  221. function createNormalizedNormalAttribute( normal ) {
  222. if ( cachedData.attributesNormalized.has( normal ) ) {
  223. return cachedData.attributesNormalized.get( normal );
  224. }
  225. var attribute = normal.clone();
  226. var v = new Vector3();
  227. for ( var i = 0, il = attribute.count; i < il; i ++ ) {
  228. v.fromBufferAttribute( attribute, i );
  229. if ( v.x === 0 && v.y === 0 && v.z === 0 ) {
  230. // if values can't be normalized set (1, 0, 0)
  231. v.setX( 1.0 );
  232. } else {
  233. v.normalize();
  234. }
  235. attribute.setXYZ( i, v.x, v.y, v.z );
  236. }
  237. cachedData.attributesNormalized.set( normal, attribute );
  238. return attribute;
  239. }
  240. /**
  241. * Get the required size + padding for a buffer, rounded to the next 4-byte boundary.
  242. * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
  243. *
  244. * @param {Integer} bufferSize The size the original buffer.
  245. * @returns {Integer} new buffer size with required padding.
  246. *
  247. */
  248. function getPaddedBufferSize( bufferSize ) {
  249. return Math.ceil( bufferSize / 4 ) * 4;
  250. }
  251. /**
  252. * Returns a buffer aligned to 4-byte boundary.
  253. *
  254. * @param {ArrayBuffer} arrayBuffer Buffer to pad
  255. * @param {Integer} paddingByte (Optional)
  256. * @returns {ArrayBuffer} The same buffer if it's already aligned to 4-byte boundary or a new buffer
  257. */
  258. function getPaddedArrayBuffer( arrayBuffer, paddingByte ) {
  259. paddingByte = paddingByte || 0;
  260. var paddedLength = getPaddedBufferSize( arrayBuffer.byteLength );
  261. if ( paddedLength !== arrayBuffer.byteLength ) {
  262. var array = new Uint8Array( paddedLength );
  263. array.set( new Uint8Array( arrayBuffer ) );
  264. if ( paddingByte !== 0 ) {
  265. for ( var i = arrayBuffer.byteLength; i < paddedLength; i ++ ) {
  266. array[ i ] = paddingByte;
  267. }
  268. }
  269. return array.buffer;
  270. }
  271. return arrayBuffer;
  272. }
  273. /**
  274. * Serializes a userData.
  275. *
  276. * @param {THREE.Object3D|THREE.Material} object
  277. * @param {Object} gltfProperty
  278. */
  279. function serializeUserData( object, gltfProperty ) {
  280. if ( Object.keys( object.userData ).length === 0 ) {
  281. return;
  282. }
  283. try {
  284. var json = JSON.parse( JSON.stringify( object.userData ) );
  285. if ( options.includeCustomExtensions && json.gltfExtensions ) {
  286. if ( gltfProperty.extensions === undefined ) {
  287. gltfProperty.extensions = {};
  288. }
  289. for ( var extensionName in json.gltfExtensions ) {
  290. gltfProperty.extensions[ extensionName ] = json.gltfExtensions[ extensionName ];
  291. extensionsUsed[ extensionName ] = true;
  292. }
  293. delete json.gltfExtensions;
  294. }
  295. if ( Object.keys( json ).length > 0 ) {
  296. gltfProperty.extras = json;
  297. }
  298. } catch ( error ) {
  299. console.warn( 'THREE.GLTFExporter: userData of \'' + object.name + '\' ' +
  300. 'won\'t be serialized because of JSON.stringify error - ' + error.message );
  301. }
  302. }
  303. /**
  304. * Applies a texture transform, if present, to the map definition. Requires
  305. * the KHR_texture_transform extension.
  306. */
  307. function applyTextureTransform( mapDef, texture ) {
  308. var didTransform = false;
  309. var transformDef = {};
  310. if ( texture.offset.x !== 0 || texture.offset.y !== 0 ) {
  311. transformDef.offset = texture.offset.toArray();
  312. didTransform = true;
  313. }
  314. if ( texture.rotation !== 0 ) {
  315. transformDef.rotation = texture.rotation;
  316. didTransform = true;
  317. }
  318. if ( texture.repeat.x !== 1 || texture.repeat.y !== 1 ) {
  319. transformDef.scale = texture.repeat.toArray();
  320. didTransform = true;
  321. }
  322. if ( didTransform ) {
  323. mapDef.extensions = mapDef.extensions || {};
  324. mapDef.extensions[ 'KHR_texture_transform' ] = transformDef;
  325. extensionsUsed[ 'KHR_texture_transform' ] = true;
  326. }
  327. }
  328. /**
  329. * Process a buffer to append to the default one.
  330. * @param {ArrayBuffer} buffer
  331. * @return {Integer}
  332. */
  333. function processBuffer( buffer ) {
  334. if ( ! outputJSON.buffers ) {
  335. outputJSON.buffers = [ { byteLength: 0 } ];
  336. }
  337. // All buffers are merged before export.
  338. buffers.push( buffer );
  339. return 0;
  340. }
  341. /**
  342. * Process and generate a BufferView
  343. * @param {BufferAttribute} attribute
  344. * @param {number} componentType
  345. * @param {number} start
  346. * @param {number} count
  347. * @param {number} target (Optional) Target usage of the BufferView
  348. * @return {Object}
  349. */
  350. function processBufferView( attribute, componentType, start, count, target ) {
  351. if ( ! outputJSON.bufferViews ) {
  352. outputJSON.bufferViews = [];
  353. }
  354. // Create a new dataview and dump the attribute's array into it
  355. var componentSize;
  356. if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {
  357. componentSize = 1;
  358. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
  359. componentSize = 2;
  360. } else {
  361. componentSize = 4;
  362. }
  363. var byteLength = getPaddedBufferSize( count * attribute.itemSize * componentSize );
  364. var dataView = new DataView( new ArrayBuffer( byteLength ) );
  365. var offset = 0;
  366. for ( var i = start; i < start + count; i ++ ) {
  367. for ( var a = 0; a < attribute.itemSize; a ++ ) {
  368. var value;
  369. if ( attribute.itemSize > 4 ) {
  370. // no support for interleaved data for itemSize > 4
  371. value = attribute.array[ i * attribute.itemSize + a ];
  372. } else {
  373. if ( a === 0 ) value = attribute.getX( i );
  374. else if ( a === 1 ) value = attribute.getY( i );
  375. else if ( a === 2 ) value = attribute.getZ( i );
  376. else if ( a === 3 ) value = attribute.getW( i );
  377. }
  378. if ( componentType === WEBGL_CONSTANTS.FLOAT ) {
  379. dataView.setFloat32( offset, value, true );
  380. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_INT ) {
  381. dataView.setUint32( offset, value, true );
  382. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
  383. dataView.setUint16( offset, value, true );
  384. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {
  385. dataView.setUint8( offset, value );
  386. }
  387. offset += componentSize;
  388. }
  389. }
  390. var gltfBufferView = {
  391. buffer: processBuffer( dataView.buffer ),
  392. byteOffset: byteOffset,
  393. byteLength: byteLength
  394. };
  395. if ( target !== undefined ) gltfBufferView.target = target;
  396. if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {
  397. // Only define byteStride for vertex attributes.
  398. gltfBufferView.byteStride = attribute.itemSize * componentSize;
  399. }
  400. byteOffset += byteLength;
  401. outputJSON.bufferViews.push( gltfBufferView );
  402. // @TODO Merge bufferViews where possible.
  403. var output = {
  404. id: outputJSON.bufferViews.length - 1,
  405. byteLength: 0
  406. };
  407. return output;
  408. }
  409. /**
  410. * Process and generate a BufferView from an image Blob.
  411. * @param {Blob} blob
  412. * @return {Promise<Integer>}
  413. */
  414. function processBufferViewImage( blob ) {
  415. if ( ! outputJSON.bufferViews ) {
  416. outputJSON.bufferViews = [];
  417. }
  418. return new Promise( function ( resolve ) {
  419. var reader = new window.FileReader();
  420. reader.readAsArrayBuffer( blob );
  421. reader.onloadend = function () {
  422. var buffer = getPaddedArrayBuffer( reader.result );
  423. var bufferView = {
  424. buffer: processBuffer( buffer ),
  425. byteOffset: byteOffset,
  426. byteLength: buffer.byteLength
  427. };
  428. byteOffset += buffer.byteLength;
  429. outputJSON.bufferViews.push( bufferView );
  430. resolve( outputJSON.bufferViews.length - 1 );
  431. };
  432. } );
  433. }
  434. /**
  435. * Process attribute to generate an accessor
  436. * @param {BufferAttribute} attribute Attribute to process
  437. * @param {BufferGeometry} geometry (Optional) Geometry used for truncated draw range
  438. * @param {Integer} start (Optional)
  439. * @param {Integer} count (Optional)
  440. * @return {Integer} Index of the processed accessor on the "accessors" array
  441. */
  442. function processAccessor( attribute, geometry, start, count ) {
  443. var types = {
  444. 1: 'SCALAR',
  445. 2: 'VEC2',
  446. 3: 'VEC3',
  447. 4: 'VEC4',
  448. 16: 'MAT4'
  449. };
  450. var componentType;
  451. // Detect the component type of the attribute array (float, uint or ushort)
  452. if ( attribute.array.constructor === Float32Array ) {
  453. componentType = WEBGL_CONSTANTS.FLOAT;
  454. } else if ( attribute.array.constructor === Uint32Array ) {
  455. componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
  456. } else if ( attribute.array.constructor === Uint16Array ) {
  457. componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
  458. } else if ( attribute.array.constructor === Uint8Array ) {
  459. componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE;
  460. } else {
  461. throw new Error( 'THREE.GLTFExporter: Unsupported bufferAttribute component type.' );
  462. }
  463. if ( start === undefined ) start = 0;
  464. if ( count === undefined ) count = attribute.count;
  465. // @TODO Indexed buffer geometry with drawRange not supported yet
  466. if ( options.truncateDrawRange && geometry !== undefined && geometry.index === null ) {
  467. var end = start + count;
  468. var end2 = geometry.drawRange.count === Infinity
  469. ? attribute.count
  470. : geometry.drawRange.start + geometry.drawRange.count;
  471. start = Math.max( start, geometry.drawRange.start );
  472. count = Math.min( end, end2 ) - start;
  473. if ( count < 0 ) count = 0;
  474. }
  475. // Skip creating an accessor if the attribute doesn't have data to export
  476. if ( count === 0 ) {
  477. return null;
  478. }
  479. var minMax = getMinMax( attribute, start, count );
  480. var bufferViewTarget;
  481. // If geometry isn't provided, don't infer the target usage of the bufferView. For
  482. // animation samplers, target must not be set.
  483. if ( geometry !== undefined ) {
  484. bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER;
  485. }
  486. var bufferView = processBufferView( attribute, componentType, start, count, bufferViewTarget );
  487. var gltfAccessor = {
  488. bufferView: bufferView.id,
  489. byteOffset: bufferView.byteOffset,
  490. componentType: componentType,
  491. count: count,
  492. max: minMax.max,
  493. min: minMax.min,
  494. type: types[ attribute.itemSize ]
  495. };
  496. if ( attribute.normalized === true ) {
  497. gltfAccessor.normalized = true;
  498. }
  499. if ( ! outputJSON.accessors ) {
  500. outputJSON.accessors = [];
  501. }
  502. outputJSON.accessors.push( gltfAccessor );
  503. return outputJSON.accessors.length - 1;
  504. }
  505. /**
  506. * Process image
  507. * @param {Image} image to process
  508. * @param {Integer} format of the image (e.g. RGBFormat, RGBAFormat etc)
  509. * @param {Boolean} flipY before writing out the image
  510. * @return {Integer} Index of the processed texture in the "images" array
  511. */
  512. function processImage( image, format, flipY ) {
  513. if ( ! cachedData.images.has( image ) ) {
  514. cachedData.images.set( image, {} );
  515. }
  516. var cachedImages = cachedData.images.get( image );
  517. var mimeType = format === RGBAFormat ? 'image/png' : 'image/jpeg';
  518. var key = mimeType + ":flipY/" + flipY.toString();
  519. if ( cachedImages[ key ] !== undefined ) {
  520. return cachedImages[ key ];
  521. }
  522. if ( ! outputJSON.images ) {
  523. outputJSON.images = [];
  524. }
  525. var gltfImage = { mimeType: mimeType };
  526. if ( options.embedImages ) {
  527. var canvas = cachedCanvas = cachedCanvas || document.createElement( 'canvas' );
  528. canvas.width = Math.min( image.width, options.maxTextureSize );
  529. canvas.height = Math.min( image.height, options.maxTextureSize );
  530. var ctx = canvas.getContext( '2d' );
  531. if ( flipY === true ) {
  532. ctx.translate( 0, canvas.height );
  533. ctx.scale( 1, - 1 );
  534. }
  535. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  536. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  537. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  538. ctx.drawImage( image, 0, 0, canvas.width, canvas.height );
  539. } else {
  540. if ( format !== RGBAFormat && format !== RGBFormat ) {
  541. console.error( 'GLTFExporter: Only RGB and RGBA formats are supported.' );
  542. }
  543. if ( image.width > options.maxTextureSize || image.height > options.maxTextureSize ) {
  544. console.warn( 'GLTFExporter: Image size is bigger than maxTextureSize', image );
  545. }
  546. let data = image.data;
  547. if ( format === RGBFormat ) {
  548. data = new Uint8ClampedArray( image.height * image.width * 4 );
  549. for ( var i = 0, j = 0; i < data.length; i += 4, j += 3 ) {
  550. data[ i + 0 ] = image.data[ j + 0 ];
  551. data[ i + 1 ] = image.data[ j + 1 ];
  552. data[ i + 2 ] = image.data[ j + 2 ];
  553. data[ i + 3 ] = 255;
  554. }
  555. }
  556. ctx.putImageData( new ImageData( data, image.width, image.height ), 0, 0 );
  557. }
  558. if ( options.binary === true ) {
  559. pending.push( new Promise( function ( resolve ) {
  560. canvas.toBlob( function ( blob ) {
  561. processBufferViewImage( blob ).then( function ( bufferViewIndex ) {
  562. gltfImage.bufferView = bufferViewIndex;
  563. resolve();
  564. } );
  565. }, mimeType );
  566. } ) );
  567. } else {
  568. gltfImage.uri = canvas.toDataURL( mimeType );
  569. }
  570. } else {
  571. gltfImage.uri = image.src;
  572. }
  573. outputJSON.images.push( gltfImage );
  574. var index = outputJSON.images.length - 1;
  575. cachedImages[ key ] = index;
  576. return index;
  577. }
  578. /**
  579. * Process sampler
  580. * @param {Texture} map Texture to process
  581. * @return {Integer} Index of the processed texture in the "samplers" array
  582. */
  583. function processSampler( map ) {
  584. if ( ! outputJSON.samplers ) {
  585. outputJSON.samplers = [];
  586. }
  587. var gltfSampler = {
  588. magFilter: THREE_TO_WEBGL[ map.magFilter ],
  589. minFilter: THREE_TO_WEBGL[ map.minFilter ],
  590. wrapS: THREE_TO_WEBGL[ map.wrapS ],
  591. wrapT: THREE_TO_WEBGL[ map.wrapT ]
  592. };
  593. outputJSON.samplers.push( gltfSampler );
  594. return outputJSON.samplers.length - 1;
  595. }
  596. /**
  597. * Process texture
  598. * @param {Texture} map Map to process
  599. * @return {Integer} Index of the processed texture in the "textures" array
  600. */
  601. function processTexture( map ) {
  602. if ( cachedData.textures.has( map ) ) {
  603. return cachedData.textures.get( map );
  604. }
  605. if ( ! outputJSON.textures ) {
  606. outputJSON.textures = [];
  607. }
  608. var gltfTexture = {
  609. sampler: processSampler( map ),
  610. source: processImage( map.image, map.format, map.flipY )
  611. };
  612. if ( map.name ) {
  613. gltfTexture.name = map.name;
  614. }
  615. outputJSON.textures.push( gltfTexture );
  616. var index = outputJSON.textures.length - 1;
  617. cachedData.textures.set( map, index );
  618. return index;
  619. }
  620. /**
  621. * Process material
  622. * @param {THREE.Material} material Material to process
  623. * @return {Integer} Index of the processed material in the "materials" array
  624. */
  625. function processMaterial( material ) {
  626. if ( cachedData.materials.has( material ) ) {
  627. return cachedData.materials.get( material );
  628. }
  629. if ( material.isShaderMaterial ) {
  630. console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' );
  631. return null;
  632. }
  633. if ( ! outputJSON.materials ) {
  634. outputJSON.materials = [];
  635. }
  636. // @QUESTION Should we avoid including any attribute that has the default value?
  637. var gltfMaterial = {
  638. pbrMetallicRoughness: {}
  639. };
  640. if ( material.isMeshBasicMaterial ) {
  641. gltfMaterial.extensions = { KHR_materials_unlit: {} };
  642. extensionsUsed[ 'KHR_materials_unlit' ] = true;
  643. } else if ( material.isGLTFSpecularGlossinessMaterial ) {
  644. gltfMaterial.extensions = { KHR_materials_pbrSpecularGlossiness: {} };
  645. extensionsUsed[ 'KHR_materials_pbrSpecularGlossiness' ] = true;
  646. } else if ( ! material.isMeshStandardMaterial ) {
  647. console.warn( 'GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.' );
  648. }
  649. // pbrMetallicRoughness.baseColorFactor
  650. var color = material.color.toArray().concat( [ material.opacity ] );
  651. if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) {
  652. gltfMaterial.pbrMetallicRoughness.baseColorFactor = color;
  653. }
  654. if ( material.isMeshStandardMaterial ) {
  655. gltfMaterial.pbrMetallicRoughness.metallicFactor = material.metalness;
  656. gltfMaterial.pbrMetallicRoughness.roughnessFactor = material.roughness;
  657. } else if ( material.isMeshBasicMaterial ) {
  658. gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.0;
  659. gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.9;
  660. } else {
  661. gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.5;
  662. gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.5;
  663. }
  664. // pbrSpecularGlossiness diffuse, specular and glossiness factor
  665. if ( material.isGLTFSpecularGlossinessMaterial ) {
  666. if ( gltfMaterial.pbrMetallicRoughness.baseColorFactor ) {
  667. gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.diffuseFactor = gltfMaterial.pbrMetallicRoughness.baseColorFactor;
  668. }
  669. var specularFactor = [ 1, 1, 1 ];
  670. material.specular.toArray( specularFactor, 0 );
  671. gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.specularFactor = specularFactor;
  672. gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.glossinessFactor = material.glossiness;
  673. }
  674. // pbrMetallicRoughness.metallicRoughnessTexture
  675. if ( material.metalnessMap || material.roughnessMap ) {
  676. if ( material.metalnessMap === material.roughnessMap ) {
  677. var metalRoughMapDef = { index: processTexture( material.metalnessMap ) };
  678. applyTextureTransform( metalRoughMapDef, material.metalnessMap );
  679. gltfMaterial.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef;
  680. } else {
  681. console.warn( 'THREE.GLTFExporter: Ignoring metalnessMap and roughnessMap because they are not the same Texture.' );
  682. }
  683. }
  684. // pbrMetallicRoughness.baseColorTexture or pbrSpecularGlossiness diffuseTexture
  685. if ( material.map ) {
  686. var baseColorMapDef = { index: processTexture( material.map ) };
  687. applyTextureTransform( baseColorMapDef, material.map );
  688. if ( material.isGLTFSpecularGlossinessMaterial ) {
  689. gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.diffuseTexture = baseColorMapDef;
  690. }
  691. gltfMaterial.pbrMetallicRoughness.baseColorTexture = baseColorMapDef;
  692. }
  693. // pbrSpecularGlossiness specular map
  694. if ( material.isGLTFSpecularGlossinessMaterial && material.specularMap ) {
  695. var specularMapDef = { index: processTexture( material.specularMap ) };
  696. applyTextureTransform( specularMapDef, material.specularMap );
  697. gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.specularGlossinessTexture = specularMapDef;
  698. }
  699. if ( material.emissive ) {
  700. // emissiveFactor
  701. var emissive = material.emissive.clone().multiplyScalar( material.emissiveIntensity ).toArray();
  702. if ( ! equalArray( emissive, [ 0, 0, 0 ] ) ) {
  703. gltfMaterial.emissiveFactor = emissive;
  704. }
  705. // emissiveTexture
  706. if ( material.emissiveMap ) {
  707. var emissiveMapDef = { index: processTexture( material.emissiveMap ) };
  708. applyTextureTransform( emissiveMapDef, material.emissiveMap );
  709. gltfMaterial.emissiveTexture = emissiveMapDef;
  710. }
  711. }
  712. // normalTexture
  713. if ( material.normalMap ) {
  714. var normalMapDef = { index: processTexture( material.normalMap ) };
  715. if ( material.normalScale && material.normalScale.x !== - 1 ) {
  716. if ( material.normalScale.x !== material.normalScale.y ) {
  717. console.warn( 'THREE.GLTFExporter: Normal scale components are different, ignoring Y and exporting X.' );
  718. }
  719. normalMapDef.scale = material.normalScale.x;
  720. }
  721. applyTextureTransform( normalMapDef, material.normalMap );
  722. gltfMaterial.normalTexture = normalMapDef;
  723. }
  724. // occlusionTexture
  725. if ( material.aoMap ) {
  726. var occlusionMapDef = {
  727. index: processTexture( material.aoMap ),
  728. texCoord: 1
  729. };
  730. if ( material.aoMapIntensity !== 1.0 ) {
  731. occlusionMapDef.strength = material.aoMapIntensity;
  732. }
  733. applyTextureTransform( occlusionMapDef, material.aoMap );
  734. gltfMaterial.occlusionTexture = occlusionMapDef;
  735. }
  736. // alphaMode
  737. if ( material.transparent ) {
  738. gltfMaterial.alphaMode = 'BLEND';
  739. } else {
  740. if ( material.alphaTest > 0.0 ) {
  741. gltfMaterial.alphaMode = 'MASK';
  742. gltfMaterial.alphaCutoff = material.alphaTest;
  743. }
  744. }
  745. // doubleSided
  746. if ( material.side === DoubleSide ) {
  747. gltfMaterial.doubleSided = true;
  748. }
  749. if ( material.name !== '' ) {
  750. gltfMaterial.name = material.name;
  751. }
  752. serializeUserData( material, gltfMaterial );
  753. outputJSON.materials.push( gltfMaterial );
  754. var index = outputJSON.materials.length - 1;
  755. cachedData.materials.set( material, index );
  756. return index;
  757. }
  758. /**
  759. * Process mesh
  760. * @param {THREE.Mesh} mesh Mesh to process
  761. * @return {Integer} Index of the processed mesh in the "meshes" array
  762. */
  763. function processMesh( mesh ) {
  764. var meshCacheKeyParts = [ mesh.geometry.uuid ];
  765. if ( Array.isArray( mesh.material ) ) {
  766. for ( var i = 0, l = mesh.material.length; i < l; i ++ ) {
  767. meshCacheKeyParts.push( mesh.material[ i ].uuid );
  768. }
  769. } else {
  770. meshCacheKeyParts.push( mesh.material.uuid );
  771. }
  772. var meshCacheKey = meshCacheKeyParts.join( ':' );
  773. if ( cachedData.meshes.has( meshCacheKey ) ) {
  774. return cachedData.meshes.get( meshCacheKey );
  775. }
  776. var geometry = mesh.geometry;
  777. var mode;
  778. // Use the correct mode
  779. if ( mesh.isLineSegments ) {
  780. mode = WEBGL_CONSTANTS.LINES;
  781. } else if ( mesh.isLineLoop ) {
  782. mode = WEBGL_CONSTANTS.LINE_LOOP;
  783. } else if ( mesh.isLine ) {
  784. mode = WEBGL_CONSTANTS.LINE_STRIP;
  785. } else if ( mesh.isPoints ) {
  786. mode = WEBGL_CONSTANTS.POINTS;
  787. } else {
  788. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
  789. }
  790. if ( ! geometry.isBufferGeometry ) {
  791. console.warn( 'GLTFExporter: Exporting THREE.Geometry will increase file size. Use BufferGeometry instead.' );
  792. geometry = new BufferGeometry().setFromObject( mesh );
  793. }
  794. var gltfMesh = {};
  795. var attributes = {};
  796. var primitives = [];
  797. var targets = [];
  798. // Conversion between attributes names in threejs and gltf spec
  799. var nameConversion = {
  800. uv: 'TEXCOORD_0',
  801. uv2: 'TEXCOORD_1',
  802. color: 'COLOR_0',
  803. skinWeight: 'WEIGHTS_0',
  804. skinIndex: 'JOINTS_0'
  805. };
  806. var originalNormal = geometry.getAttribute( 'normal' );
  807. if ( originalNormal !== undefined && ! isNormalizedNormalAttribute( originalNormal ) ) {
  808. console.warn( 'THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.' );
  809. geometry.setAttribute( 'normal', createNormalizedNormalAttribute( originalNormal ) );
  810. }
  811. // @QUESTION Detect if .vertexColors = true?
  812. // For every attribute create an accessor
  813. var modifiedAttribute = null;
  814. for ( var attributeName in geometry.attributes ) {
  815. // Ignore morph target attributes, which are exported later.
  816. if ( attributeName.substr( 0, 5 ) === 'morph' ) continue;
  817. var attribute = geometry.attributes[ attributeName ];
  818. attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
  819. // Prefix all geometry attributes except the ones specifically
  820. // listed in the spec; non-spec attributes are considered custom.
  821. var validVertexAttributes =
  822. /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;
  823. if ( ! validVertexAttributes.test( attributeName ) ) {
  824. attributeName = '_' + attributeName;
  825. }
  826. if ( cachedData.attributes.has( getUID( attribute ) ) ) {
  827. attributes[ attributeName ] = cachedData.attributes.get( getUID( attribute ) );
  828. continue;
  829. }
  830. // JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT.
  831. modifiedAttribute = null;
  832. var array = attribute.array;
  833. if ( attributeName === 'JOINTS_0' &&
  834. ! ( array instanceof Uint16Array ) &&
  835. ! ( array instanceof Uint8Array ) ) {
  836. console.warn( 'GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.' );
  837. modifiedAttribute = new BufferAttribute( new Uint16Array( array ), attribute.itemSize, attribute.normalized );
  838. }
  839. var accessor = processAccessor( modifiedAttribute || attribute, geometry );
  840. if ( accessor !== null ) {
  841. attributes[ attributeName ] = accessor;
  842. cachedData.attributes.set( getUID( attribute ), accessor );
  843. }
  844. }
  845. if ( originalNormal !== undefined ) geometry.setAttribute( 'normal', originalNormal );
  846. // Skip if no exportable attributes found
  847. if ( Object.keys( attributes ).length === 0 ) {
  848. return null;
  849. }
  850. // Morph targets
  851. if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) {
  852. var weights = [];
  853. var targetNames = [];
  854. var reverseDictionary = {};
  855. if ( mesh.morphTargetDictionary !== undefined ) {
  856. for ( var key in mesh.morphTargetDictionary ) {
  857. reverseDictionary[ mesh.morphTargetDictionary[ key ] ] = key;
  858. }
  859. }
  860. for ( var i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {
  861. var target = {};
  862. var warned = false;
  863. for ( var attributeName in geometry.morphAttributes ) {
  864. // glTF 2.0 morph supports only POSITION/NORMAL/TANGENT.
  865. // Three.js doesn't support TANGENT yet.
  866. if ( attributeName !== 'position' && attributeName !== 'normal' ) {
  867. if ( ! warned ) {
  868. console.warn( 'GLTFExporter: Only POSITION and NORMAL morph are supported.' );
  869. warned = true;
  870. }
  871. continue;
  872. }
  873. var attribute = geometry.morphAttributes[ attributeName ][ i ];
  874. var gltfAttributeName = attributeName.toUpperCase();
  875. // Three.js morph attribute has absolute values while the one of glTF has relative values.
  876. //
  877. // glTF 2.0 Specification:
  878. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets
  879. var baseAttribute = geometry.attributes[ attributeName ];
  880. if ( cachedData.attributes.has( getUID( attribute ) ) ) {
  881. target[ gltfAttributeName ] = cachedData.attributes.get( getUID( attribute ) );
  882. continue;
  883. }
  884. // Clones attribute not to override
  885. var relativeAttribute = attribute.clone();
  886. if ( ! geometry.morphTargetsRelative ) {
  887. for ( var j = 0, jl = attribute.count; j < jl; j ++ ) {
  888. relativeAttribute.setXYZ(
  889. j,
  890. attribute.getX( j ) - baseAttribute.getX( j ),
  891. attribute.getY( j ) - baseAttribute.getY( j ),
  892. attribute.getZ( j ) - baseAttribute.getZ( j )
  893. );
  894. }
  895. }
  896. target[ gltfAttributeName ] = processAccessor( relativeAttribute, geometry );
  897. cachedData.attributes.set( getUID( baseAttribute ), target[ gltfAttributeName ] );
  898. }
  899. targets.push( target );
  900. weights.push( mesh.morphTargetInfluences[ i ] );
  901. if ( mesh.morphTargetDictionary !== undefined ) targetNames.push( reverseDictionary[ i ] );
  902. }
  903. gltfMesh.weights = weights;
  904. if ( targetNames.length > 0 ) {
  905. gltfMesh.extras = {};
  906. gltfMesh.extras.targetNames = targetNames;
  907. }
  908. }
  909. var isMultiMaterial = Array.isArray( mesh.material );
  910. if ( isMultiMaterial && geometry.groups.length === 0 ) return null;
  911. var materials = isMultiMaterial ? mesh.material : [ mesh.material ];
  912. var groups = isMultiMaterial ? geometry.groups : [ { materialIndex: 0, start: undefined, count: undefined } ];
  913. for ( var i = 0, il = groups.length; i < il; i ++ ) {
  914. var primitive = {
  915. mode: mode,
  916. attributes: attributes,
  917. };
  918. serializeUserData( geometry, primitive );
  919. if ( targets.length > 0 ) primitive.targets = targets;
  920. if ( geometry.index !== null ) {
  921. var cacheKey = getUID( geometry.index );
  922. if ( groups[ i ].start !== undefined || groups[ i ].count !== undefined ) {
  923. cacheKey += ':' + groups[ i ].start + ':' + groups[ i ].count;
  924. }
  925. if ( cachedData.attributes.has( cacheKey ) ) {
  926. primitive.indices = cachedData.attributes.get( cacheKey );
  927. } else {
  928. primitive.indices = processAccessor( geometry.index, geometry, groups[ i ].start, groups[ i ].count );
  929. cachedData.attributes.set( cacheKey, primitive.indices );
  930. }
  931. if ( primitive.indices === null ) delete primitive.indices;
  932. }
  933. var material = processMaterial( materials[ groups[ i ].materialIndex ] );
  934. if ( material !== null ) {
  935. primitive.material = material;
  936. }
  937. primitives.push( primitive );
  938. }
  939. gltfMesh.primitives = primitives;
  940. if ( ! outputJSON.meshes ) {
  941. outputJSON.meshes = [];
  942. }
  943. outputJSON.meshes.push( gltfMesh );
  944. var index = outputJSON.meshes.length - 1;
  945. cachedData.meshes.set( meshCacheKey, index );
  946. return index;
  947. }
  948. /**
  949. * Process camera
  950. * @param {THREE.Camera} camera Camera to process
  951. * @return {Integer} Index of the processed mesh in the "camera" array
  952. */
  953. function processCamera( camera ) {
  954. if ( ! outputJSON.cameras ) {
  955. outputJSON.cameras = [];
  956. }
  957. var isOrtho = camera.isOrthographicCamera;
  958. var gltfCamera = {
  959. type: isOrtho ? 'orthographic' : 'perspective'
  960. };
  961. if ( isOrtho ) {
  962. gltfCamera.orthographic = {
  963. xmag: camera.right * 2,
  964. ymag: camera.top * 2,
  965. zfar: camera.far <= 0 ? 0.001 : camera.far,
  966. znear: camera.near < 0 ? 0 : camera.near
  967. };
  968. } else {
  969. gltfCamera.perspective = {
  970. aspectRatio: camera.aspect,
  971. yfov: MathUtils.degToRad( camera.fov ),
  972. zfar: camera.far <= 0 ? 0.001 : camera.far,
  973. znear: camera.near < 0 ? 0 : camera.near
  974. };
  975. }
  976. if ( camera.name !== '' ) {
  977. gltfCamera.name = camera.type;
  978. }
  979. outputJSON.cameras.push( gltfCamera );
  980. return outputJSON.cameras.length - 1;
  981. }
  982. /**
  983. * Creates glTF animation entry from AnimationClip object.
  984. *
  985. * Status:
  986. * - Only properties listed in PATH_PROPERTIES may be animated.
  987. *
  988. * @param {THREE.AnimationClip} clip
  989. * @param {THREE.Object3D} root
  990. * @return {number}
  991. */
  992. function processAnimation( clip, root ) {
  993. if ( ! outputJSON.animations ) {
  994. outputJSON.animations = [];
  995. }
  996. clip = GLTFExporter.Utils.mergeMorphTargetTracks( clip.clone(), root );
  997. var tracks = clip.tracks;
  998. var channels = [];
  999. var samplers = [];
  1000. for ( var i = 0; i < tracks.length; ++ i ) {
  1001. var track = tracks[ i ];
  1002. var trackBinding = PropertyBinding.parseTrackName( track.name );
  1003. var trackNode = PropertyBinding.findNode( root, trackBinding.nodeName );
  1004. var trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];
  1005. if ( trackBinding.objectName === 'bones' ) {
  1006. if ( trackNode.isSkinnedMesh === true ) {
  1007. trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );
  1008. } else {
  1009. trackNode = undefined;
  1010. }
  1011. }
  1012. if ( ! trackNode || ! trackProperty ) {
  1013. console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
  1014. return null;
  1015. }
  1016. var inputItemSize = 1;
  1017. var outputItemSize = track.values.length / track.times.length;
  1018. if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {
  1019. outputItemSize /= trackNode.morphTargetInfluences.length;
  1020. }
  1021. var interpolation;
  1022. // @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE
  1023. // Detecting glTF cubic spline interpolant by checking factory method's special property
  1024. // GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return
  1025. // valid value from .getInterpolation().
  1026. if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) {
  1027. interpolation = 'CUBICSPLINE';
  1028. // itemSize of CUBICSPLINE keyframe is 9
  1029. // (VEC3 * 3: inTangent, splineVertex, and outTangent)
  1030. // but needs to be stored as VEC3 so dividing by 3 here.
  1031. outputItemSize /= 3;
  1032. } else if ( track.getInterpolation() === InterpolateDiscrete ) {
  1033. interpolation = 'STEP';
  1034. } else {
  1035. interpolation = 'LINEAR';
  1036. }
  1037. samplers.push( {
  1038. input: processAccessor( new BufferAttribute( track.times, inputItemSize ) ),
  1039. output: processAccessor( new BufferAttribute( track.values, outputItemSize ) ),
  1040. interpolation: interpolation
  1041. } );
  1042. channels.push( {
  1043. sampler: samplers.length - 1,
  1044. target: {
  1045. node: nodeMap.get( trackNode ),
  1046. path: trackProperty
  1047. }
  1048. } );
  1049. }
  1050. outputJSON.animations.push( {
  1051. name: clip.name || 'clip_' + outputJSON.animations.length,
  1052. samplers: samplers,
  1053. channels: channels
  1054. } );
  1055. return outputJSON.animations.length - 1;
  1056. }
  1057. function processSkin( object ) {
  1058. var node = outputJSON.nodes[ nodeMap.get( object ) ];
  1059. var skeleton = object.skeleton;
  1060. if ( skeleton === undefined ) return null;
  1061. var rootJoint = object.skeleton.bones[ 0 ];
  1062. if ( rootJoint === undefined ) return null;
  1063. var joints = [];
  1064. var inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );
  1065. var temporaryBoneInverse = new Matrix4();
  1066. for ( var i = 0; i < skeleton.bones.length; ++ i ) {
  1067. joints.push( nodeMap.get( skeleton.bones[ i ] ) );
  1068. temporaryBoneInverse.copy( skeleton.boneInverses[ i ] );
  1069. temporaryBoneInverse.multiply( object.bindMatrix ).toArray( inverseBindMatrices, i * 16 );
  1070. }
  1071. if ( outputJSON.skins === undefined ) {
  1072. outputJSON.skins = [];
  1073. }
  1074. outputJSON.skins.push( {
  1075. inverseBindMatrices: processAccessor( new BufferAttribute( inverseBindMatrices, 16 ) ),
  1076. joints: joints,
  1077. skeleton: nodeMap.get( rootJoint )
  1078. } );
  1079. var skinIndex = node.skin = outputJSON.skins.length - 1;
  1080. return skinIndex;
  1081. }
  1082. function processLight( light ) {
  1083. var lightDef = {};
  1084. if ( light.name ) lightDef.name = light.name;
  1085. lightDef.color = light.color.toArray();
  1086. lightDef.intensity = light.intensity;
  1087. if ( light.isDirectionalLight ) {
  1088. lightDef.type = 'directional';
  1089. } else if ( light.isPointLight ) {
  1090. lightDef.type = 'point';
  1091. if ( light.distance > 0 ) lightDef.range = light.distance;
  1092. } else if ( light.isSpotLight ) {
  1093. lightDef.type = 'spot';
  1094. if ( light.distance > 0 ) lightDef.range = light.distance;
  1095. lightDef.spot = {};
  1096. lightDef.spot.innerConeAngle = ( light.penumbra - 1.0 ) * light.angle * - 1.0;
  1097. lightDef.spot.outerConeAngle = light.angle;
  1098. }
  1099. if ( light.decay !== undefined && light.decay !== 2 ) {
  1100. console.warn( 'THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, '
  1101. + 'and expects light.decay=2.' );
  1102. }
  1103. if ( light.target
  1104. && ( light.target.parent !== light
  1105. || light.target.position.x !== 0
  1106. || light.target.position.y !== 0
  1107. || light.target.position.z !== - 1 ) ) {
  1108. console.warn( 'THREE.GLTFExporter: Light direction may be lost. For best results, '
  1109. + 'make light.target a child of the light with position 0,0,-1.' );
  1110. }
  1111. var lights = outputJSON.extensions[ 'KHR_lights_punctual' ].lights;
  1112. lights.push( lightDef );
  1113. return lights.length - 1;
  1114. }
  1115. /**
  1116. * Process Object3D node
  1117. * @param {THREE.Object3D} node Object3D to processNode
  1118. * @return {Integer} Index of the node in the nodes list
  1119. */
  1120. function processNode( object ) {
  1121. if ( ! outputJSON.nodes ) {
  1122. outputJSON.nodes = [];
  1123. }
  1124. var gltfNode = {};
  1125. if ( options.trs ) {
  1126. var rotation = object.quaternion.toArray();
  1127. var position = object.position.toArray();
  1128. var scale = object.scale.toArray();
  1129. if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
  1130. gltfNode.rotation = rotation;
  1131. }
  1132. if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
  1133. gltfNode.translation = position;
  1134. }
  1135. if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
  1136. gltfNode.scale = scale;
  1137. }
  1138. } else {
  1139. if ( object.matrixAutoUpdate ) {
  1140. object.updateMatrix();
  1141. }
  1142. if ( isIdentityMatrix( object.matrix ) === false ) {
  1143. gltfNode.matrix = object.matrix.elements;
  1144. }
  1145. }
  1146. // We don't export empty strings name because it represents no-name in Three.js.
  1147. if ( object.name !== '' ) {
  1148. gltfNode.name = String( object.name );
  1149. }
  1150. serializeUserData( object, gltfNode );
  1151. if ( object.isMesh || object.isLine || object.isPoints ) {
  1152. var mesh = processMesh( object );
  1153. if ( mesh !== null ) {
  1154. gltfNode.mesh = mesh;
  1155. }
  1156. } else if ( object.isCamera ) {
  1157. gltfNode.camera = processCamera( object );
  1158. } else if ( object.isDirectionalLight || object.isPointLight || object.isSpotLight ) {
  1159. if ( ! extensionsUsed[ 'KHR_lights_punctual' ] ) {
  1160. outputJSON.extensions = outputJSON.extensions || {};
  1161. outputJSON.extensions[ 'KHR_lights_punctual' ] = { lights: [] };
  1162. extensionsUsed[ 'KHR_lights_punctual' ] = true;
  1163. }
  1164. gltfNode.extensions = gltfNode.extensions || {};
  1165. gltfNode.extensions[ 'KHR_lights_punctual' ] = { light: processLight( object ) };
  1166. } else if ( object.isLight ) {
  1167. console.warn( 'THREE.GLTFExporter: Only directional, point, and spot lights are supported.', object );
  1168. return null;
  1169. }
  1170. if ( object.isSkinnedMesh ) {
  1171. skins.push( object );
  1172. }
  1173. if ( object.children.length > 0 ) {
  1174. var children = [];
  1175. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  1176. var child = object.children[ i ];
  1177. if ( child.visible || options.onlyVisible === false ) {
  1178. var node = processNode( child );
  1179. if ( node !== null ) {
  1180. children.push( node );
  1181. }
  1182. }
  1183. }
  1184. if ( children.length > 0 ) {
  1185. gltfNode.children = children;
  1186. }
  1187. }
  1188. outputJSON.nodes.push( gltfNode );
  1189. var nodeIndex = outputJSON.nodes.length - 1;
  1190. nodeMap.set( object, nodeIndex );
  1191. return nodeIndex;
  1192. }
  1193. /**
  1194. * Process Scene
  1195. * @param {Scene} node Scene to process
  1196. */
  1197. function processScene( scene ) {
  1198. if ( ! outputJSON.scenes ) {
  1199. outputJSON.scenes = [];
  1200. outputJSON.scene = 0;
  1201. }
  1202. var gltfScene = {};
  1203. if ( scene.name !== '' ) {
  1204. gltfScene.name = scene.name;
  1205. }
  1206. outputJSON.scenes.push( gltfScene );
  1207. var nodes = [];
  1208. for ( var i = 0, l = scene.children.length; i < l; i ++ ) {
  1209. var child = scene.children[ i ];
  1210. if ( child.visible || options.onlyVisible === false ) {
  1211. var node = processNode( child );
  1212. if ( node !== null ) {
  1213. nodes.push( node );
  1214. }
  1215. }
  1216. }
  1217. if ( nodes.length > 0 ) {
  1218. gltfScene.nodes = nodes;
  1219. }
  1220. serializeUserData( scene, gltfScene );
  1221. }
  1222. /**
  1223. * Creates a Scene to hold a list of objects and parse it
  1224. * @param {Array} objects List of objects to process
  1225. */
  1226. function processObjects( objects ) {
  1227. var scene = new Scene();
  1228. scene.name = 'AuxScene';
  1229. for ( var i = 0; i < objects.length; i ++ ) {
  1230. // We push directly to children instead of calling `add` to prevent
  1231. // modify the .parent and break its original scene and hierarchy
  1232. scene.children.push( objects[ i ] );
  1233. }
  1234. processScene( scene );
  1235. }
  1236. function processInput( input ) {
  1237. input = input instanceof Array ? input : [ input ];
  1238. var objectsWithoutScene = [];
  1239. for ( var i = 0; i < input.length; i ++ ) {
  1240. if ( input[ i ] instanceof Scene ) {
  1241. processScene( input[ i ] );
  1242. } else {
  1243. objectsWithoutScene.push( input[ i ] );
  1244. }
  1245. }
  1246. if ( objectsWithoutScene.length > 0 ) {
  1247. processObjects( objectsWithoutScene );
  1248. }
  1249. for ( var i = 0; i < skins.length; ++ i ) {
  1250. processSkin( skins[ i ] );
  1251. }
  1252. for ( var i = 0; i < options.animations.length; ++ i ) {
  1253. processAnimation( options.animations[ i ], input[ 0 ] );
  1254. }
  1255. }
  1256. processInput( input );
  1257. Promise.all( pending ).then( function () {
  1258. // Merge buffers.
  1259. var blob = new Blob( buffers, { type: 'application/octet-stream' } );
  1260. // Declare extensions.
  1261. var extensionsUsedList = Object.keys( extensionsUsed );
  1262. if ( extensionsUsedList.length > 0 ) outputJSON.extensionsUsed = extensionsUsedList;
  1263. // Update bytelength of the single buffer.
  1264. if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) outputJSON.buffers[ 0 ].byteLength = blob.size;
  1265. if ( options.binary === true ) {
  1266. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
  1267. var GLB_HEADER_BYTES = 12;
  1268. var GLB_HEADER_MAGIC = 0x46546C67;
  1269. var GLB_VERSION = 2;
  1270. var GLB_CHUNK_PREFIX_BYTES = 8;
  1271. var GLB_CHUNK_TYPE_JSON = 0x4E4F534A;
  1272. var GLB_CHUNK_TYPE_BIN = 0x004E4942;
  1273. var reader = new window.FileReader();
  1274. reader.readAsArrayBuffer( blob );
  1275. reader.onloadend = function () {
  1276. // Binary chunk.
  1277. var binaryChunk = getPaddedArrayBuffer( reader.result );
  1278. var binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  1279. binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true );
  1280. binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true );
  1281. // JSON chunk.
  1282. var jsonChunk = getPaddedArrayBuffer( stringToArrayBuffer( JSON.stringify( outputJSON ) ), 0x20 );
  1283. var jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  1284. jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true );
  1285. jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true );
  1286. // GLB header.
  1287. var header = new ArrayBuffer( GLB_HEADER_BYTES );
  1288. var headerView = new DataView( header );
  1289. headerView.setUint32( 0, GLB_HEADER_MAGIC, true );
  1290. headerView.setUint32( 4, GLB_VERSION, true );
  1291. var totalByteLength = GLB_HEADER_BYTES
  1292. + jsonChunkPrefix.byteLength + jsonChunk.byteLength
  1293. + binaryChunkPrefix.byteLength + binaryChunk.byteLength;
  1294. headerView.setUint32( 8, totalByteLength, true );
  1295. var glbBlob = new Blob( [
  1296. header,
  1297. jsonChunkPrefix,
  1298. jsonChunk,
  1299. binaryChunkPrefix,
  1300. binaryChunk
  1301. ], { type: 'application/octet-stream' } );
  1302. var glbReader = new window.FileReader();
  1303. glbReader.readAsArrayBuffer( glbBlob );
  1304. glbReader.onloadend = function () {
  1305. onDone( glbReader.result );
  1306. };
  1307. };
  1308. } else {
  1309. if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) {
  1310. var reader = new window.FileReader();
  1311. reader.readAsDataURL( blob );
  1312. reader.onloadend = function () {
  1313. var base64data = reader.result;
  1314. outputJSON.buffers[ 0 ].uri = base64data;
  1315. onDone( outputJSON );
  1316. };
  1317. } else {
  1318. onDone( outputJSON );
  1319. }
  1320. }
  1321. } );
  1322. }
  1323. };
  1324. GLTFExporter.Utils = {
  1325. insertKeyframe: function ( track, time ) {
  1326. var tolerance = 0.001; // 1ms
  1327. var valueSize = track.getValueSize();
  1328. var times = new track.TimeBufferType( track.times.length + 1 );
  1329. var values = new track.ValueBufferType( track.values.length + valueSize );
  1330. var interpolant = track.createInterpolant( new track.ValueBufferType( valueSize ) );
  1331. var index;
  1332. if ( track.times.length === 0 ) {
  1333. times[ 0 ] = time;
  1334. for ( var i = 0; i < valueSize; i ++ ) {
  1335. values[ i ] = 0;
  1336. }
  1337. index = 0;
  1338. } else if ( time < track.times[ 0 ] ) {
  1339. if ( Math.abs( track.times[ 0 ] - time ) < tolerance ) return 0;
  1340. times[ 0 ] = time;
  1341. times.set( track.times, 1 );
  1342. values.set( interpolant.evaluate( time ), 0 );
  1343. values.set( track.values, valueSize );
  1344. index = 0;
  1345. } else if ( time > track.times[ track.times.length - 1 ] ) {
  1346. if ( Math.abs( track.times[ track.times.length - 1 ] - time ) < tolerance ) {
  1347. return track.times.length - 1;
  1348. }
  1349. times[ times.length - 1 ] = time;
  1350. times.set( track.times, 0 );
  1351. values.set( track.values, 0 );
  1352. values.set( interpolant.evaluate( time ), track.values.length );
  1353. index = times.length - 1;
  1354. } else {
  1355. for ( var i = 0; i < track.times.length; i ++ ) {
  1356. if ( Math.abs( track.times[ i ] - time ) < tolerance ) return i;
  1357. if ( track.times[ i ] < time && track.times[ i + 1 ] > time ) {
  1358. times.set( track.times.slice( 0, i + 1 ), 0 );
  1359. times[ i + 1 ] = time;
  1360. times.set( track.times.slice( i + 1 ), i + 2 );
  1361. values.set( track.values.slice( 0, ( i + 1 ) * valueSize ), 0 );
  1362. values.set( interpolant.evaluate( time ), ( i + 1 ) * valueSize );
  1363. values.set( track.values.slice( ( i + 1 ) * valueSize ), ( i + 2 ) * valueSize );
  1364. index = i + 1;
  1365. break;
  1366. }
  1367. }
  1368. }
  1369. track.times = times;
  1370. track.values = values;
  1371. return index;
  1372. },
  1373. mergeMorphTargetTracks: function ( clip, root ) {
  1374. var tracks = [];
  1375. var mergedTracks = {};
  1376. var sourceTracks = clip.tracks;
  1377. for ( var i = 0; i < sourceTracks.length; ++ i ) {
  1378. var sourceTrack = sourceTracks[ i ];
  1379. var sourceTrackBinding = PropertyBinding.parseTrackName( sourceTrack.name );
  1380. var sourceTrackNode = PropertyBinding.findNode( root, sourceTrackBinding.nodeName );
  1381. if ( sourceTrackBinding.propertyName !== 'morphTargetInfluences' || sourceTrackBinding.propertyIndex === undefined ) {
  1382. // Tracks that don't affect morph targets, or that affect all morph targets together, can be left as-is.
  1383. tracks.push( sourceTrack );
  1384. continue;
  1385. }
  1386. if ( sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete
  1387. && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear ) {
  1388. if ( sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  1389. // This should never happen, because glTF morph target animations
  1390. // affect all targets already.
  1391. throw new Error( 'THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.' );
  1392. }
  1393. console.warn( 'THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead.' );
  1394. sourceTrack = sourceTrack.clone();
  1395. sourceTrack.setInterpolation( InterpolateLinear );
  1396. }
  1397. var targetCount = sourceTrackNode.morphTargetInfluences.length;
  1398. var targetIndex = sourceTrackNode.morphTargetDictionary[ sourceTrackBinding.propertyIndex ];
  1399. if ( targetIndex === undefined ) {
  1400. throw new Error( 'THREE.GLTFExporter: Morph target name not found: ' + sourceTrackBinding.propertyIndex );
  1401. }
  1402. var mergedTrack;
  1403. // If this is the first time we've seen this object, create a new
  1404. // track to store merged keyframe data for each morph target.
  1405. if ( mergedTracks[ sourceTrackNode.uuid ] === undefined ) {
  1406. mergedTrack = sourceTrack.clone();
  1407. var values = new mergedTrack.ValueBufferType( targetCount * mergedTrack.times.length );
  1408. for ( var j = 0; j < mergedTrack.times.length; j ++ ) {
  1409. values[ j * targetCount + targetIndex ] = mergedTrack.values[ j ];
  1410. }
  1411. // We need to take into consideration the intended target node
  1412. // of our original un-merged morphTarget animation.
  1413. mergedTrack.name = sourceTrackBinding.nodeName + '.morphTargetInfluences';
  1414. mergedTrack.values = values;
  1415. mergedTracks[ sourceTrackNode.uuid ] = mergedTrack;
  1416. tracks.push( mergedTrack );
  1417. continue;
  1418. }
  1419. var sourceInterpolant = sourceTrack.createInterpolant( new sourceTrack.ValueBufferType( 1 ) );
  1420. mergedTrack = mergedTracks[ sourceTrackNode.uuid ];
  1421. // For every existing keyframe of the merged track, write a (possibly
  1422. // interpolated) value from the source track.
  1423. for ( var j = 0; j < mergedTrack.times.length; j ++ ) {
  1424. mergedTrack.values[ j * targetCount + targetIndex ] = sourceInterpolant.evaluate( mergedTrack.times[ j ] );
  1425. }
  1426. // For every existing keyframe of the source track, write a (possibly
  1427. // new) keyframe to the merged track. Values from the previous loop may
  1428. // be written again, but keyframes are de-duplicated.
  1429. for ( var j = 0; j < sourceTrack.times.length; j ++ ) {
  1430. var keyframeIndex = this.insertKeyframe( mergedTrack, sourceTrack.times[ j ] );
  1431. mergedTrack.values[ keyframeIndex * targetCount + targetIndex ] = sourceTrack.values[ j ];
  1432. }
  1433. }
  1434. clip.tracks = tracks;
  1435. return clip;
  1436. }
  1437. };
  1438. export { GLTFExporter };