GLTFExporter.js 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607
  1. /**
  2. * @author fernandojsg / http://fernandojsg.com
  3. * @author Don McCurdy / https://www.donmccurdy.com
  4. * @author Takahiro / https://github.com/takahirox
  5. */
  6. //------------------------------------------------------------------------------
  7. // Constants
  8. //------------------------------------------------------------------------------
  9. var WEBGL_CONSTANTS = {
  10. POINTS: 0x0000,
  11. LINES: 0x0001,
  12. LINE_LOOP: 0x0002,
  13. LINE_STRIP: 0x0003,
  14. TRIANGLES: 0x0004,
  15. TRIANGLE_STRIP: 0x0005,
  16. TRIANGLE_FAN: 0x0006,
  17. UNSIGNED_BYTE: 0x1401,
  18. UNSIGNED_SHORT: 0x1403,
  19. FLOAT: 0x1406,
  20. UNSIGNED_INT: 0x1405,
  21. ARRAY_BUFFER: 0x8892,
  22. ELEMENT_ARRAY_BUFFER: 0x8893,
  23. NEAREST: 0x2600,
  24. LINEAR: 0x2601,
  25. NEAREST_MIPMAP_NEAREST: 0x2700,
  26. LINEAR_MIPMAP_NEAREST: 0x2701,
  27. NEAREST_MIPMAP_LINEAR: 0x2702,
  28. LINEAR_MIPMAP_LINEAR: 0x2703
  29. };
  30. var THREE_TO_WEBGL = {
  31. // @TODO Replace with computed property name [THREE.*] when available on es6
  32. 1003: WEBGL_CONSTANTS.NEAREST,
  33. 1004: WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST,
  34. 1005: WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR,
  35. 1006: WEBGL_CONSTANTS.LINEAR,
  36. 1007: WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST,
  37. 1008: WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR
  38. };
  39. var PATH_PROPERTIES = {
  40. scale: 'scale',
  41. position: 'translation',
  42. quaternion: 'rotation',
  43. morphTargetInfluences: 'weights'
  44. };
  45. //------------------------------------------------------------------------------
  46. // GLTF Exporter
  47. //------------------------------------------------------------------------------
  48. THREE.GLTFExporter = function () {};
  49. THREE.GLTFExporter.prototype = {
  50. constructor: THREE.GLTFExporter,
  51. /**
  52. * Parse scenes and generate GLTF output
  53. * @param {THREE.Scene or [THREE.Scenes]} input THREE.Scene or Array of THREE.Scenes
  54. * @param {Function} onDone Callback on completed
  55. * @param {Object} options options
  56. */
  57. parse: function ( input, onDone, options ) {
  58. var DEFAULT_OPTIONS = {
  59. trs: false,
  60. onlyVisible: true,
  61. truncateDrawRange: true,
  62. embedImages: true,
  63. animations: [],
  64. forceIndices: false,
  65. forcePowerOfTwoTextures: false
  66. };
  67. options = Object.assign( {}, DEFAULT_OPTIONS, options );
  68. if ( options.animations.length > 0 ) {
  69. // Only TRS properties, and not matrices, may be targeted by animation.
  70. options.trs = true;
  71. }
  72. var outputJSON = {
  73. asset: {
  74. version: "2.0",
  75. generator: "THREE.GLTFExporter"
  76. }
  77. };
  78. var byteOffset = 0;
  79. var buffers = [];
  80. var pending = [];
  81. var nodeMap = {};
  82. var skins = [];
  83. var cachedData = {
  84. materials: {},
  85. textures: {}
  86. };
  87. var cachedCanvas;
  88. /**
  89. * Compare two arrays
  90. */
  91. /**
  92. * Compare two arrays
  93. * @param {Array} array1 Array 1 to compare
  94. * @param {Array} array2 Array 2 to compare
  95. * @return {Boolean} Returns true if both arrays are equal
  96. */
  97. function equalArray( array1, array2 ) {
  98. return ( array1.length === array2.length ) && array1.every( function ( element, index ) {
  99. return element === array2[ index ];
  100. } );
  101. }
  102. /**
  103. * Converts a string to an ArrayBuffer.
  104. * @param {string} text
  105. * @return {ArrayBuffer}
  106. */
  107. function stringToArrayBuffer( text, padded ) {
  108. if ( padded ) {
  109. var pad = getPaddedBufferSize( text.length ) - text.length;
  110. for ( var i = 0; i < pad; i++ ) {
  111. text += ' ';
  112. }
  113. }
  114. if ( window.TextEncoder !== undefined ) {
  115. return new TextEncoder().encode( text ).buffer;
  116. }
  117. var buffer = new ArrayBuffer( text.length );
  118. var bufferView = new Uint8Array( buffer );
  119. for ( var i = 0; i < text.length; ++ i ) {
  120. bufferView[ i ] = text.charCodeAt( i );
  121. }
  122. return buffer;
  123. }
  124. /**
  125. * Get the min and max vectors from the given attribute
  126. * @param {THREE.BufferAttribute} attribute Attribute to find the min/max
  127. * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
  128. */
  129. function getMinMax( attribute ) {
  130. var output = {
  131. min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
  132. max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
  133. };
  134. for ( var i = 0; i < attribute.count; i ++ ) {
  135. for ( var a = 0; a < attribute.itemSize; a ++ ) {
  136. var value = attribute.array[ i * attribute.itemSize + a ];
  137. output.min[ a ] = Math.min( output.min[ a ], value );
  138. output.max[ a ] = Math.max( output.max[ a ], value );
  139. }
  140. }
  141. return output;
  142. }
  143. /**
  144. * Checks if image size is POT.
  145. *
  146. * @param {Image} image The image to be checked.
  147. * @returns {Boolean} Returns true if image size is POT.
  148. *
  149. */
  150. function isPowerOfTwo( image ) {
  151. return THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height );
  152. }
  153. /**
  154. * Get the required size + padding for a buffer, rounded to the next 4-byte boundary.
  155. * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
  156. *
  157. * @param {Integer} bufferSize The size the original buffer.
  158. * @returns {Integer} new buffer size with required padding.
  159. *
  160. */
  161. function getPaddedBufferSize( bufferSize ) {
  162. return Math.ceil( bufferSize / 4 ) * 4;
  163. }
  164. /**
  165. * Returns a buffer aligned to 4-byte boundary.
  166. *
  167. * @param {ArrayBuffer} arrayBuffer Buffer to pad
  168. * @param {Integer} padByte (Optional)
  169. * @returns {ArrayBuffer} The same buffer if it's already aligned to 4-byte boundary or a new buffer
  170. */
  171. function getPaddedArrayBuffer( arrayBuffer, padByte ) {
  172. padByte = padByte || 0;
  173. var paddedLength = getPaddedBufferSize( arrayBuffer.byteLength );
  174. if ( paddedLength !== arrayBuffer.byteLength ) {
  175. var array = new Uint8Array( paddedLength );
  176. array.set( new Uint8Array( arrayBuffer ) );
  177. if ( padByte !== 0 ) {
  178. for ( var i = arrayBuffer.byteLength; i < paddedLength; i < il ) {
  179. array[ i ] = padByte;
  180. }
  181. }
  182. return array.buffer;
  183. }
  184. return arrayBuffer;
  185. }
  186. /**
  187. * Process a buffer to append to the default one.
  188. * @param {ArrayBuffer} buffer
  189. * @return {Integer}
  190. */
  191. function processBuffer( buffer ) {
  192. if ( ! outputJSON.buffers ) {
  193. outputJSON.buffers = [ { byteLength: 0 } ];
  194. }
  195. // All buffers are merged before export.
  196. buffers.push( buffer );
  197. return 0;
  198. }
  199. /**
  200. * Process and generate a BufferView
  201. * @param {THREE.BufferAttribute} attribute
  202. * @param {number} componentType
  203. * @param {number} start
  204. * @param {number} count
  205. * @param {number} target (Optional) Target usage of the BufferView
  206. * @return {Object}
  207. */
  208. function processBufferView( attribute, componentType, start, count, target ) {
  209. if ( ! outputJSON.bufferViews ) {
  210. outputJSON.bufferViews = [];
  211. }
  212. // Create a new dataview and dump the attribute's array into it
  213. var componentSize = componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ? 2 : 4;
  214. var byteLength = getPaddedBufferSize( count * attribute.itemSize * componentSize );
  215. var dataView = new DataView( new ArrayBuffer( byteLength ) );
  216. var offset = 0;
  217. for ( var i = start; i < start + count; i ++ ) {
  218. for ( var a = 0; a < attribute.itemSize; a ++ ) {
  219. // @TODO Fails on InterleavedBufferAttribute, and could probably be
  220. // optimized for normal BufferAttribute.
  221. var value = attribute.array[ i * attribute.itemSize + a ];
  222. if ( componentType === WEBGL_CONSTANTS.FLOAT ) {
  223. dataView.setFloat32( offset, value, true );
  224. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_INT ) {
  225. dataView.setUint32( offset, value, true );
  226. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
  227. dataView.setUint16( offset, value, true );
  228. }
  229. offset += componentSize;
  230. }
  231. }
  232. var gltfBufferView = {
  233. buffer: processBuffer( dataView.buffer ),
  234. byteOffset: byteOffset,
  235. byteLength: byteLength
  236. };
  237. if ( target !== undefined ) gltfBufferView.target = target;
  238. if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {
  239. // Only define byteStride for vertex attributes.
  240. gltfBufferView.byteStride = attribute.itemSize * componentSize;
  241. }
  242. byteOffset += byteLength;
  243. outputJSON.bufferViews.push( gltfBufferView );
  244. // @TODO Merge bufferViews where possible.
  245. var output = {
  246. id: outputJSON.bufferViews.length - 1,
  247. byteLength: 0
  248. };
  249. return output;
  250. }
  251. /**
  252. * Process and generate a BufferView from an image Blob.
  253. * @param {Blob} blob
  254. * @return {Promise<Integer>}
  255. */
  256. function processBufferViewImage( blob ) {
  257. if ( ! outputJSON.bufferViews ) {
  258. outputJSON.bufferViews = [];
  259. }
  260. return new Promise( function ( resolve ) {
  261. var reader = new window.FileReader();
  262. reader.readAsArrayBuffer( blob );
  263. reader.onloadend = function () {
  264. var buffer = getPaddedArrayBuffer( reader.result );
  265. var bufferView = {
  266. buffer: processBuffer( buffer ),
  267. byteOffset: byteOffset,
  268. byteLength: buffer.byteLength
  269. };
  270. byteOffset += buffer.byteLength;
  271. outputJSON.bufferViews.push( bufferView );
  272. resolve( outputJSON.bufferViews.length - 1 );
  273. };
  274. } );
  275. }
  276. /**
  277. * Process attribute to generate an accessor
  278. * @param {THREE.BufferAttribute} attribute Attribute to process
  279. * @param {THREE.BufferGeometry} geometry (Optional) Geometry used for truncated draw range
  280. * @return {Integer} Index of the processed accessor on the "accessors" array
  281. */
  282. function processAccessor( attribute, geometry ) {
  283. if ( ! outputJSON.accessors ) {
  284. outputJSON.accessors = [];
  285. }
  286. var types = {
  287. 1: 'SCALAR',
  288. 2: 'VEC2',
  289. 3: 'VEC3',
  290. 4: 'VEC4',
  291. 16: 'MAT4'
  292. };
  293. var componentType;
  294. // Detect the component type of the attribute array (float, uint or ushort)
  295. if ( attribute.array.constructor === Float32Array ) {
  296. componentType = WEBGL_CONSTANTS.FLOAT;
  297. } else if ( attribute.array.constructor === Uint32Array ) {
  298. componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
  299. } else if ( attribute.array.constructor === Uint16Array ) {
  300. componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
  301. } else {
  302. throw new Error( 'THREE.GLTFExporter: Unsupported bufferAttribute component type.' );
  303. }
  304. var minMax = getMinMax( attribute );
  305. var start = 0;
  306. var count = attribute.count;
  307. // @TODO Indexed buffer geometry with drawRange not supported yet
  308. if ( options.truncateDrawRange && geometry !== undefined && geometry.index === null ) {
  309. start = geometry.drawRange.start;
  310. count = geometry.drawRange.count !== Infinity ? geometry.drawRange.count : attribute.count;
  311. }
  312. var bufferViewTarget;
  313. // If geometry isn't provided, don't infer the target usage of the bufferView. For
  314. // animation samplers, target must not be set.
  315. if ( geometry !== undefined ) {
  316. var isVertexAttributes = componentType === WEBGL_CONSTANTS.FLOAT;
  317. bufferViewTarget = isVertexAttributes ? WEBGL_CONSTANTS.ARRAY_BUFFER : WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER;
  318. }
  319. var bufferView = processBufferView( attribute, componentType, start, count, bufferViewTarget );
  320. var gltfAccessor = {
  321. bufferView: bufferView.id,
  322. byteOffset: bufferView.byteOffset,
  323. componentType: componentType,
  324. count: count,
  325. max: minMax.max,
  326. min: minMax.min,
  327. type: types[ attribute.itemSize ]
  328. };
  329. outputJSON.accessors.push( gltfAccessor );
  330. return outputJSON.accessors.length - 1;
  331. }
  332. /**
  333. * Process image
  334. * @param {Texture} map Texture to process
  335. * @return {Integer} Index of the processed texture in the "images" array
  336. */
  337. function processImage( map ) {
  338. // @TODO Cache
  339. if ( ! outputJSON.images ) {
  340. outputJSON.images = [];
  341. }
  342. var mimeType = map.format === THREE.RGBAFormat ? 'image/png' : 'image/jpeg';
  343. var gltfImage = { mimeType: mimeType };
  344. if ( options.embedImages ) {
  345. var canvas = cachedCanvas = cachedCanvas || document.createElement( 'canvas' );
  346. canvas.width = map.image.width;
  347. canvas.height = map.image.height;
  348. if ( options.forcePowerOfTwoTextures && ! isPowerOfTwo( map.image ) ) {
  349. console.warn( 'GLTFExporter: Resized non-power-of-two image.', map.image );
  350. canvas.width = THREE.Math.floorPowerOfTwo( canvas.width );
  351. canvas.height = THREE.Math.floorPowerOfTwo( canvas.height );
  352. }
  353. var ctx = canvas.getContext( '2d' );
  354. if ( map.flipY === true ) {
  355. ctx.translate( 0, canvas.height );
  356. ctx.scale( 1, - 1 );
  357. }
  358. ctx.drawImage( map.image, 0, 0, canvas.width, canvas.height );
  359. if ( options.binary === true ) {
  360. pending.push( new Promise( function ( resolve ) {
  361. canvas.toBlob( function ( blob ) {
  362. processBufferViewImage( blob ).then( function ( bufferViewIndex ) {
  363. gltfImage.bufferView = bufferViewIndex;
  364. resolve();
  365. } );
  366. }, mimeType );
  367. } ) );
  368. } else {
  369. gltfImage.uri = canvas.toDataURL( mimeType );
  370. }
  371. } else {
  372. gltfImage.uri = map.image.src;
  373. }
  374. outputJSON.images.push( gltfImage );
  375. return outputJSON.images.length - 1;
  376. }
  377. /**
  378. * Process sampler
  379. * @param {Texture} map Texture to process
  380. * @return {Integer} Index of the processed texture in the "samplers" array
  381. */
  382. function processSampler( map ) {
  383. if ( ! outputJSON.samplers ) {
  384. outputJSON.samplers = [];
  385. }
  386. var gltfSampler = {
  387. magFilter: THREE_TO_WEBGL[ map.magFilter ],
  388. minFilter: THREE_TO_WEBGL[ map.minFilter ],
  389. wrapS: THREE_TO_WEBGL[ map.wrapS ],
  390. wrapT: THREE_TO_WEBGL[ map.wrapT ]
  391. };
  392. outputJSON.samplers.push( gltfSampler );
  393. return outputJSON.samplers.length - 1;
  394. }
  395. /**
  396. * Process texture
  397. * @param {Texture} map Map to process
  398. * @return {Integer} Index of the processed texture in the "textures" array
  399. */
  400. function processTexture( map ) {
  401. if ( cachedData.textures[ map.uuid ] !== undefined ) {
  402. return cachedData.textures[ map.uuid ];
  403. }
  404. if ( ! outputJSON.textures ) {
  405. outputJSON.textures = [];
  406. }
  407. var gltfTexture = {
  408. sampler: processSampler( map ),
  409. source: processImage( map )
  410. };
  411. outputJSON.textures.push( gltfTexture );
  412. var index = outputJSON.textures.length - 1;
  413. cachedData.textures[ map.uuid ] = index;
  414. return index;
  415. }
  416. /**
  417. * Process material
  418. * @param {THREE.Material} material Material to process
  419. * @return {Integer} Index of the processed material in the "materials" array
  420. */
  421. function processMaterial( material ) {
  422. if ( cachedData.materials[ material.uuid ] !== undefined ) {
  423. return cachedData.materials[ material.uuid ];
  424. }
  425. if ( ! outputJSON.materials ) {
  426. outputJSON.materials = [];
  427. }
  428. if ( material instanceof THREE.ShaderMaterial ) {
  429. console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' );
  430. return null;
  431. }
  432. if ( ! ( material instanceof THREE.MeshStandardMaterial ) ) {
  433. console.warn( 'GLTFExporter: Currently just THREE.MeshStandardMaterial is supported. Material conversion may lose information.' );
  434. }
  435. // @QUESTION Should we avoid including any attribute that has the default value?
  436. var gltfMaterial = {
  437. pbrMetallicRoughness: {}
  438. };
  439. // pbrMetallicRoughness.baseColorFactor
  440. var color = material.color.toArray().concat( [ material.opacity ] );
  441. if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) {
  442. gltfMaterial.pbrMetallicRoughness.baseColorFactor = color;
  443. }
  444. if ( material instanceof THREE.MeshStandardMaterial ) {
  445. gltfMaterial.pbrMetallicRoughness.metallicFactor = material.metalness;
  446. gltfMaterial.pbrMetallicRoughness.roughnessFactor = material.roughness;
  447. } else {
  448. gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.5;
  449. gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.5;
  450. }
  451. // pbrMetallicRoughness.metallicRoughnessTexture
  452. if ( material.metalnessMap || material.roughnessMap ) {
  453. if ( material.metalnessMap === material.roughnessMap ) {
  454. gltfMaterial.pbrMetallicRoughness.metallicRoughnessTexture = {
  455. index: processTexture( material.metalnessMap )
  456. };
  457. } else {
  458. console.warn( 'THREE.GLTFExporter: Ignoring metalnessMap and roughnessMap because they are not the same Texture.' );
  459. }
  460. }
  461. // pbrMetallicRoughness.baseColorTexture
  462. if ( material.map ) {
  463. gltfMaterial.pbrMetallicRoughness.baseColorTexture = {
  464. index: processTexture( material.map )
  465. };
  466. }
  467. if ( material instanceof THREE.MeshBasicMaterial ||
  468. material instanceof THREE.LineBasicMaterial ||
  469. material instanceof THREE.PointsMaterial ) {
  470. } else {
  471. // emissiveFactor
  472. var emissive = material.emissive.clone().multiplyScalar( material.emissiveIntensity ).toArray();
  473. if ( ! equalArray( emissive, [ 0, 0, 0 ] ) ) {
  474. gltfMaterial.emissiveFactor = emissive;
  475. }
  476. // emissiveTexture
  477. if ( material.emissiveMap ) {
  478. gltfMaterial.emissiveTexture = {
  479. index: processTexture( material.emissiveMap )
  480. };
  481. }
  482. }
  483. // normalTexture
  484. if ( material.normalMap ) {
  485. gltfMaterial.normalTexture = {
  486. index: processTexture( material.normalMap )
  487. };
  488. if ( material.normalScale.x !== - 1 ) {
  489. if ( material.normalScale.x !== material.normalScale.y ) {
  490. console.warn( 'THREE.GLTFExporter: Normal scale components are different, ignoring Y and exporting X.' );
  491. }
  492. gltfMaterial.normalTexture.scale = material.normalScale.x;
  493. }
  494. }
  495. // occlusionTexture
  496. if ( material.aoMap ) {
  497. gltfMaterial.occlusionTexture = {
  498. index: processTexture( material.aoMap )
  499. };
  500. if ( material.aoMapIntensity !== 1.0 ) {
  501. gltfMaterial.occlusionTexture.strength = material.aoMapIntensity;
  502. }
  503. }
  504. // alphaMode
  505. if ( material.transparent || material.alphaTest > 0.0 ) {
  506. gltfMaterial.alphaMode = material.opacity < 1.0 ? 'BLEND' : 'MASK';
  507. // Write alphaCutoff if it's non-zero and different from the default (0.5).
  508. if ( material.alphaTest > 0.0 && material.alphaTest !== 0.5 ) {
  509. gltfMaterial.alphaCutoff = material.alphaTest;
  510. }
  511. }
  512. // doubleSided
  513. if ( material.side === THREE.DoubleSide ) {
  514. gltfMaterial.doubleSided = true;
  515. }
  516. if ( material.name !== '' ) {
  517. gltfMaterial.name = material.name;
  518. }
  519. outputJSON.materials.push( gltfMaterial );
  520. var index = outputJSON.materials.length - 1;
  521. cachedData.materials[ material.uuid ] = index;
  522. return index;
  523. }
  524. /**
  525. * Process mesh
  526. * @param {THREE.Mesh} mesh Mesh to process
  527. * @return {Integer} Index of the processed mesh in the "meshes" array
  528. */
  529. function processMesh( mesh ) {
  530. if ( ! outputJSON.meshes ) {
  531. outputJSON.meshes = [];
  532. }
  533. var geometry = mesh.geometry;
  534. var mode;
  535. // Use the correct mode
  536. if ( mesh instanceof THREE.LineSegments ) {
  537. mode = WEBGL_CONSTANTS.LINES;
  538. } else if ( mesh instanceof THREE.LineLoop ) {
  539. mode = WEBGL_CONSTANTS.LINE_LOOP;
  540. } else if ( mesh instanceof THREE.Line ) {
  541. mode = WEBGL_CONSTANTS.LINE_STRIP;
  542. } else if ( mesh instanceof THREE.Points ) {
  543. mode = WEBGL_CONSTANTS.POINTS;
  544. } else {
  545. if ( ! geometry.isBufferGeometry ) {
  546. var geometryTemp = new THREE.BufferGeometry();
  547. geometryTemp.fromGeometry( geometry );
  548. geometry = geometryTemp;
  549. }
  550. if ( mesh.drawMode === THREE.TriangleFanDrawMode ) {
  551. console.warn( 'GLTFExporter: TriangleFanDrawMode and wireframe incompatible.' );
  552. mode = WEBGL_CONSTANTS.TRIANGLE_FAN;
  553. } else if ( mesh.drawMode === THREE.TriangleStripDrawMode ) {
  554. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINE_STRIP : WEBGL_CONSTANTS.TRIANGLE_STRIP;
  555. } else {
  556. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
  557. }
  558. }
  559. var gltfMesh = {
  560. primitives: [
  561. {
  562. mode: mode,
  563. attributes: {},
  564. }
  565. ]
  566. };
  567. var material = processMaterial( mesh.material );
  568. if ( material !== null ) {
  569. gltfMesh.primitives[ 0 ].material = material;
  570. }
  571. if ( geometry.index ) {
  572. gltfMesh.primitives[ 0 ].indices = processAccessor( geometry.index, geometry );
  573. } else if ( options.forceIndices ) {
  574. var numFaces = geometry.attributes.position.count;
  575. var indices = new Uint32Array( numFaces );
  576. for ( var i = 0; i < numFaces; i ++ ) {
  577. indices[ i ] = i;
  578. }
  579. gltfMesh.primitives[ 0 ].indices = processAccessor( new THREE.Uint32BufferAttribute( indices, 1 ), geometry );
  580. }
  581. // We've just one primitive per mesh
  582. var gltfAttributes = gltfMesh.primitives[ 0 ].attributes;
  583. // Conversion between attributes names in threejs and gltf spec
  584. var nameConversion = {
  585. uv: 'TEXCOORD_0',
  586. uv2: 'TEXCOORD_1',
  587. color: 'COLOR_0',
  588. skinWeight: 'WEIGHTS_0',
  589. skinIndex: 'JOINTS_0'
  590. };
  591. // @QUESTION Detect if .vertexColors = THREE.VertexColors?
  592. // For every attribute create an accessor
  593. for ( var attributeName in geometry.attributes ) {
  594. var attribute = geometry.attributes[ attributeName ];
  595. attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
  596. if ( attributeName.substr( 0, 5 ) !== 'MORPH' ) {
  597. gltfAttributes[ attributeName ] = processAccessor( attribute, geometry );
  598. }
  599. }
  600. // Morph targets
  601. if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) {
  602. var weights = [];
  603. var targetNames = [];
  604. var reverseDictionary = {};
  605. if ( mesh.morphTargetDictionary !== undefined ) {
  606. for ( var key in mesh.morphTargetDictionary ) {
  607. reverseDictionary[ mesh.morphTargetDictionary[ key ] ] = key;
  608. }
  609. }
  610. gltfMesh.primitives[ 0 ].targets = [];
  611. for ( var i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {
  612. var target = {};
  613. var warned = false;
  614. for ( var attributeName in geometry.morphAttributes ) {
  615. // glTF 2.0 morph supports only POSITION/NORMAL/TANGENT.
  616. // Three.js doesn't support TANGENT yet.
  617. if ( attributeName !== 'position' && attributeName !== 'normal' ) {
  618. if ( ! warned ) {
  619. console.warn( 'GLTFExporter: Only POSITION and NORMAL morph are supported.' );
  620. warned = true;
  621. }
  622. continue;
  623. }
  624. var attribute = geometry.morphAttributes[ attributeName ][ i ];
  625. // Three.js morph attribute has absolute values while the one of glTF has relative values.
  626. //
  627. // glTF 2.0 Specification:
  628. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets
  629. var baseAttribute = geometry.attributes[ attributeName ];
  630. // Clones attribute not to override
  631. var relativeAttribute = attribute.clone();
  632. for ( var j = 0, jl = attribute.count; j < jl; j ++ ) {
  633. relativeAttribute.setXYZ(
  634. j,
  635. attribute.getX( j ) - baseAttribute.getX( j ),
  636. attribute.getY( j ) - baseAttribute.getY( j ),
  637. attribute.getZ( j ) - baseAttribute.getZ( j )
  638. );
  639. }
  640. target[ attributeName.toUpperCase() ] = processAccessor( relativeAttribute, geometry );
  641. }
  642. gltfMesh.primitives[ 0 ].targets.push( target );
  643. weights.push( mesh.morphTargetInfluences[ i ] );
  644. if ( mesh.morphTargetDictionary !== undefined ) targetNames.push( reverseDictionary[ i ] );
  645. }
  646. gltfMesh.weights = weights;
  647. if ( targetNames.length > 0 ) {
  648. gltfMesh.extras = {};
  649. gltfMesh.extras.targetNames = targetNames;
  650. }
  651. }
  652. outputJSON.meshes.push( gltfMesh );
  653. return outputJSON.meshes.length - 1;
  654. }
  655. /**
  656. * Process camera
  657. * @param {THREE.Camera} camera Camera to process
  658. * @return {Integer} Index of the processed mesh in the "camera" array
  659. */
  660. function processCamera( camera ) {
  661. if ( ! outputJSON.cameras ) {
  662. outputJSON.cameras = [];
  663. }
  664. var isOrtho = camera instanceof THREE.OrthographicCamera;
  665. var gltfCamera = {
  666. type: isOrtho ? 'orthographic' : 'perspective'
  667. };
  668. if ( isOrtho ) {
  669. gltfCamera.orthographic = {
  670. xmag: camera.right * 2,
  671. ymag: camera.top * 2,
  672. zfar: camera.far <= 0 ? 0.001 : camera.far,
  673. znear: camera.near < 0 ? 0 : camera.near
  674. };
  675. } else {
  676. gltfCamera.perspective = {
  677. aspectRatio: camera.aspect,
  678. yfov: THREE.Math.degToRad( camera.fov ) / camera.aspect,
  679. zfar: camera.far <= 0 ? 0.001 : camera.far,
  680. znear: camera.near < 0 ? 0 : camera.near
  681. };
  682. }
  683. if ( camera.name !== '' ) {
  684. gltfCamera.name = camera.type;
  685. }
  686. outputJSON.cameras.push( gltfCamera );
  687. return outputJSON.cameras.length - 1;
  688. }
  689. /**
  690. * Creates glTF animation entry from AnimationClip object.
  691. *
  692. * Status:
  693. * - Only properties listed in PATH_PROPERTIES may be animated.
  694. *
  695. * @param {THREE.AnimationClip} clip
  696. * @param {THREE.Object3D} root
  697. * @return {number}
  698. */
  699. function processAnimation( clip, root ) {
  700. if ( ! outputJSON.animations ) {
  701. outputJSON.animations = [];
  702. }
  703. var channels = [];
  704. var samplers = [];
  705. for ( var i = 0; i < clip.tracks.length; ++ i ) {
  706. var track = clip.tracks[ i ];
  707. var trackBinding = THREE.PropertyBinding.parseTrackName( track.name );
  708. var trackNode = THREE.PropertyBinding.findNode( root, trackBinding.nodeName );
  709. var trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];
  710. if ( trackBinding.objectName === 'bones' ) {
  711. if ( trackNode.isSkinnedMesh === true ) {
  712. trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );
  713. } else {
  714. trackNode = undefined;
  715. }
  716. }
  717. if ( ! trackNode || ! trackProperty ) {
  718. console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
  719. return null;
  720. }
  721. var inputItemSize = 1;
  722. var outputItemSize = track.values.length / track.times.length;
  723. if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {
  724. outputItemSize /= trackNode.morphTargetInfluences.length;
  725. }
  726. var interpolation;
  727. // @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE
  728. // Detecting glTF cubic spline interpolant by checking factory method's special property
  729. // GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return
  730. // valid value from .getInterpolation().
  731. if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) {
  732. interpolation = 'CUBICSPLINE';
  733. // itemSize of CUBICSPLINE keyframe is 9
  734. // (VEC3 * 3: inTangent, splineVertex, and outTangent)
  735. // but needs to be stored as VEC3 so dividing by 3 here.
  736. outputItemSize /= 3;
  737. } else if ( track.getInterpolation() === THREE.InterpolateDiscrete ) {
  738. interpolation = 'STEP';
  739. } else {
  740. interpolation = 'LINEAR';
  741. }
  742. samplers.push( {
  743. input: processAccessor( new THREE.BufferAttribute( track.times, inputItemSize ) ),
  744. output: processAccessor( new THREE.BufferAttribute( track.values, outputItemSize ) ),
  745. interpolation: interpolation
  746. } );
  747. channels.push( {
  748. sampler: samplers.length - 1,
  749. target: {
  750. node: nodeMap[ trackNode.uuid ],
  751. path: trackProperty
  752. }
  753. } );
  754. }
  755. outputJSON.animations.push( {
  756. name: clip.name || 'clip_' + outputJSON.animations.length,
  757. samplers: samplers,
  758. channels: channels
  759. } );
  760. return outputJSON.animations.length - 1;
  761. }
  762. function processSkin( object ) {
  763. var node = outputJSON.nodes[ nodeMap[ object.uuid ] ];
  764. var skeleton = object.skeleton;
  765. var rootJoint = object.skeleton.bones[ 0 ];
  766. if ( rootJoint === undefined ) return null;
  767. var joints = [];
  768. var inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );
  769. for ( var i = 0; i < skeleton.bones.length; ++ i ) {
  770. joints.push( nodeMap[ skeleton.bones[ i ].uuid ] );
  771. skeleton.boneInverses[ i ].toArray( inverseBindMatrices, i * 16 );
  772. }
  773. if ( outputJSON.skins === undefined ) {
  774. outputJSON.skins = [];
  775. }
  776. outputJSON.skins.push( {
  777. inverseBindMatrices: processAccessor( new THREE.BufferAttribute( inverseBindMatrices, 16 ) ),
  778. joints: joints,
  779. skeleton: nodeMap[ rootJoint.uuid ]
  780. } );
  781. var skinIndex = node.skin = outputJSON.skins.length - 1;
  782. return skinIndex;
  783. }
  784. /**
  785. * Process Object3D node
  786. * @param {THREE.Object3D} node Object3D to processNode
  787. * @return {Integer} Index of the node in the nodes list
  788. */
  789. function processNode( object ) {
  790. if ( object instanceof THREE.Light ) {
  791. console.warn( 'GLTFExporter: Unsupported node type:', object.constructor.name );
  792. return null;
  793. }
  794. if ( ! outputJSON.nodes ) {
  795. outputJSON.nodes = [];
  796. }
  797. var gltfNode = {};
  798. if ( options.trs ) {
  799. var rotation = object.quaternion.toArray();
  800. var position = object.position.toArray();
  801. var scale = object.scale.toArray();
  802. if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
  803. gltfNode.rotation = rotation;
  804. }
  805. if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
  806. gltfNode.translation = position;
  807. }
  808. if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
  809. gltfNode.scale = scale;
  810. }
  811. } else {
  812. object.updateMatrix();
  813. if ( ! equalArray( object.matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] ) ) {
  814. gltfNode.matrix = object.matrix.elements;
  815. }
  816. }
  817. // We don't export empty strings name because it represents no-name in Three.js.
  818. if ( object.name !== '' ) {
  819. gltfNode.name = String( object.name );
  820. }
  821. if ( object.userData && Object.keys( object.userData ).length > 0 ) {
  822. try {
  823. gltfNode.extras = JSON.parse( JSON.stringify( object.userData ) );
  824. } catch ( e ) {
  825. throw new Error( 'THREE.GLTFExporter: userData can\'t be serialized' );
  826. }
  827. }
  828. if ( object instanceof THREE.Mesh ||
  829. object instanceof THREE.Line ||
  830. object instanceof THREE.Points ) {
  831. gltfNode.mesh = processMesh( object );
  832. } else if ( object instanceof THREE.Camera ) {
  833. gltfNode.camera = processCamera( object );
  834. }
  835. if ( object instanceof THREE.SkinnedMesh ) {
  836. skins.push( object );
  837. }
  838. if ( object.children.length > 0 ) {
  839. var children = [];
  840. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  841. var child = object.children[ i ];
  842. if ( child.visible || options.onlyVisible === false ) {
  843. var node = processNode( child );
  844. if ( node !== null ) {
  845. children.push( node );
  846. }
  847. }
  848. }
  849. if ( children.length > 0 ) {
  850. gltfNode.children = children;
  851. }
  852. }
  853. outputJSON.nodes.push( gltfNode );
  854. var nodeIndex = nodeMap[ object.uuid ] = outputJSON.nodes.length - 1;
  855. return nodeIndex;
  856. }
  857. /**
  858. * Process Scene
  859. * @param {THREE.Scene} node Scene to process
  860. */
  861. function processScene( scene ) {
  862. if ( ! outputJSON.scenes ) {
  863. outputJSON.scenes = [];
  864. outputJSON.scene = 0;
  865. }
  866. var gltfScene = {
  867. nodes: []
  868. };
  869. if ( scene.name !== '' ) {
  870. gltfScene.name = scene.name;
  871. }
  872. outputJSON.scenes.push( gltfScene );
  873. var nodes = [];
  874. for ( var i = 0, l = scene.children.length; i < l; i ++ ) {
  875. var child = scene.children[ i ];
  876. if ( child.visible || options.onlyVisible === false ) {
  877. var node = processNode( child );
  878. if ( node !== null ) {
  879. nodes.push( node );
  880. }
  881. }
  882. }
  883. if ( nodes.length > 0 ) {
  884. gltfScene.nodes = nodes;
  885. }
  886. }
  887. /**
  888. * Creates a THREE.Scene to hold a list of objects and parse it
  889. * @param {Array} objects List of objects to process
  890. */
  891. function processObjects( objects ) {
  892. var scene = new THREE.Scene();
  893. scene.name = 'AuxScene';
  894. for ( var i = 0; i < objects.length; i ++ ) {
  895. // We push directly to children instead of calling `add` to prevent
  896. // modify the .parent and break its original scene and hierarchy
  897. scene.children.push( objects[ i ] );
  898. }
  899. processScene( scene );
  900. }
  901. function processInput( input ) {
  902. input = input instanceof Array ? input : [ input ];
  903. var objectsWithoutScene = [];
  904. for ( var i = 0; i < input.length; i ++ ) {
  905. if ( input[ i ] instanceof THREE.Scene ) {
  906. processScene( input[ i ] );
  907. } else {
  908. objectsWithoutScene.push( input[ i ] );
  909. }
  910. }
  911. if ( objectsWithoutScene.length > 0 ) {
  912. processObjects( objectsWithoutScene );
  913. }
  914. for ( var i = 0; i < skins.length; ++ i ) {
  915. processSkin( skins[ i ] );
  916. }
  917. for ( var i = 0; i < options.animations.length; ++ i ) {
  918. processAnimation( options.animations[ i ], input[ 0 ] );
  919. }
  920. }
  921. processInput( input );
  922. Promise.all( pending ).then( function () {
  923. // Merge buffers.
  924. var blob = new Blob( buffers, { type: 'application/octet-stream' } );
  925. if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) {
  926. // Update bytelength of the single buffer.
  927. outputJSON.buffers[ 0 ].byteLength = blob.size;
  928. var reader = new window.FileReader();
  929. if ( options.binary === true ) {
  930. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
  931. var GLB_HEADER_BYTES = 12;
  932. var GLB_HEADER_MAGIC = 0x46546C67;
  933. var GLB_VERSION = 2;
  934. var GLB_CHUNK_PREFIX_BYTES = 8;
  935. var GLB_CHUNK_TYPE_JSON = 0x4E4F534A;
  936. var GLB_CHUNK_TYPE_BIN = 0x004E4942;
  937. reader.readAsArrayBuffer( blob );
  938. reader.onloadend = function () {
  939. // Binary chunk.
  940. var binaryChunk = getPaddedArrayBuffer( reader.result );
  941. var binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  942. binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true );
  943. binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true );
  944. // JSON chunk.
  945. var jsonChunk = getPaddedArrayBuffer( stringToArrayBuffer( JSON.stringify( outputJSON ), true ), 0x20 );
  946. var jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  947. jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true );
  948. jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true );
  949. // GLB header.
  950. var header = new ArrayBuffer( GLB_HEADER_BYTES );
  951. var headerView = new DataView( header );
  952. headerView.setUint32( 0, GLB_HEADER_MAGIC, true );
  953. headerView.setUint32( 4, GLB_VERSION, true );
  954. var totalByteLength = GLB_HEADER_BYTES
  955. + jsonChunkPrefix.byteLength + jsonChunk.byteLength
  956. + binaryChunkPrefix.byteLength + binaryChunk.byteLength;
  957. headerView.setUint32( 8, totalByteLength, true );
  958. var glbBlob = new Blob( [
  959. header,
  960. jsonChunkPrefix,
  961. jsonChunk,
  962. binaryChunkPrefix,
  963. binaryChunk
  964. ], { type: 'application/octet-stream' } );
  965. var glbReader = new window.FileReader();
  966. glbReader.readAsArrayBuffer( glbBlob );
  967. glbReader.onloadend = function () {
  968. onDone( glbReader.result );
  969. };
  970. };
  971. } else {
  972. reader.readAsDataURL( blob );
  973. reader.onloadend = function () {
  974. var base64data = reader.result;
  975. outputJSON.buffers[ 0 ].uri = base64data;
  976. onDone( outputJSON );
  977. };
  978. }
  979. } else {
  980. onDone( outputJSON );
  981. }
  982. } );
  983. }
  984. };