GLTFExporter.js 34 KB

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