GLTFExporter.js 29 KB

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