GLTFExporter.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  1. /**
  2. * @author fernandojsg / http://fernandojsg.com
  3. */
  4. //------------------------------------------------------------------------------
  5. // GLTF Exporter
  6. //------------------------------------------------------------------------------
  7. THREE.GLTFExporter = function ( renderer ) {
  8. this.renderer = renderer;
  9. };
  10. THREE.GLTFExporter.prototype = {
  11. constructor: THREE.GLTFExporter,
  12. /**
  13. * Parse scenes and generate GLTF output
  14. * @param {THREE.Scene or [THREE.Scenes]} input THREE.Scene or Array of THREE.Scenes
  15. * @param {Function} onDone Callback on completed
  16. * @param {Object} options options
  17. * trs: Exports position, rotation and scale instead of matrix
  18. */
  19. parse: function ( input, onDone, options ) {
  20. options = options || {};
  21. var glUtils = new THREE.WebGLUtils( this.renderer.context, this.renderer.extensions );
  22. var gl = this.renderer.context;
  23. var outputJSON = {
  24. asset: {
  25. version: "2.0",
  26. generator: "THREE.JS GLTFExporter" // @QUESTION Does it support spaces?
  27. }
  28. };
  29. var byteOffset = 0;
  30. var dataViews = [];
  31. /**
  32. * Compare two arrays
  33. */
  34. /**
  35. * Compare two arrays
  36. * @param {Array} array1 Array 1 to compare
  37. * @param {Array} array2 Array 2 to compare
  38. * @return {Boolean} Returns true if both arrays are equal
  39. */
  40. function equalArray ( array1, array2 ) {
  41. return ( array1.length === array2.length ) && array1.every( function( element, index ) {
  42. return element === array2[ index ];
  43. });
  44. }
  45. /**
  46. * Get the min and he max vectors from the given attribute
  47. * @param {THREE.WebGLAttribute} attribute Attribute to find the min/max
  48. * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
  49. */
  50. function getMinMax ( attribute ) {
  51. var output = {
  52. min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
  53. max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
  54. };
  55. for ( var i = 0; i < attribute.count; i++ ) {
  56. for ( var a = 0; a < attribute.itemSize; a++ ) {
  57. var value = attribute.array[ i * attribute.itemSize + a ];
  58. output.min[ a ] = Math.min( output.min[ a ], value );
  59. output.max[ a ] = Math.max( output.max[ a ], value );
  60. }
  61. }
  62. return output;
  63. }
  64. /**
  65. * Process a buffer to append to the default one.
  66. * @param {THREE.BufferAttribute} attribute Attribute to store
  67. * @param {Integer} componentType Component type (Unsigned short, unsigned int or float)
  68. * @return {Integer} Index of the buffer created (Currently always 0)
  69. */
  70. function processBuffer ( attribute, componentType ) {
  71. if ( !outputJSON.buffers ) {
  72. outputJSON.buffers = [
  73. {
  74. byteLength: 0,
  75. uri: ''
  76. }
  77. ];
  78. }
  79. // Create a new dataview and dump the attribute's array into it
  80. var dataView = new DataView( new ArrayBuffer( attribute.array.byteLength ) );
  81. var offset = 0;
  82. var offsetInc = componentType === gl.UNSIGNED_SHORT ? 2 : 4;
  83. for ( var i = 0; i < attribute.count; i++ ) {
  84. for (var a = 0; a < attribute.itemSize; a++ ) {
  85. var value = attribute.array[ i * attribute.itemSize + a ];
  86. if ( componentType === gl.FLOAT ) {
  87. dataView.setFloat32( offset, value, true );
  88. } else if ( componentType === gl.UNSIGNED_INT ) {
  89. dataView.setUint8( offset, value, true );
  90. } else if ( componentType === gl.UNSIGNED_SHORT ) {
  91. dataView.setUint16( offset, value, true );
  92. }
  93. offset += offsetInc;
  94. }
  95. }
  96. // We just use one buffer
  97. dataViews.push( dataView );
  98. // Always using just one buffer
  99. return 0;
  100. }
  101. /**
  102. * Process and generate a BufferView
  103. * @param {[type]} data [description]
  104. * @return {[type]} [description]
  105. */
  106. function processBufferView ( data, componentType ) {
  107. var isVertexAttributes = componentType === gl.FLOAT;
  108. if ( !outputJSON.bufferViews ) {
  109. outputJSON.bufferViews = [];
  110. }
  111. var gltfBufferView = {
  112. buffer: processBuffer( data, componentType ),
  113. byteOffset: byteOffset,
  114. byteLength: data.array.byteLength,
  115. byteStride: data.itemSize * ( componentType === gl.UNSIGNED_SHORT ? 2 : 4 ),
  116. target: isVertexAttributes ? gl.ARRAY_BUFFER : gl.ELEMENT_ARRAY_BUFFER
  117. };
  118. byteOffset += data.array.byteLength;
  119. outputJSON.bufferViews.push( gltfBufferView );
  120. // @TODO Ideally we'll have just two bufferviews: 0 is for vertex attributes, 1 for indices
  121. var output = {
  122. id: outputJSON.bufferViews.length - 1,
  123. byteLength: 0
  124. };
  125. return output;
  126. }
  127. /**
  128. * Process attribute to generate an accessor
  129. * @param {THREE.WebGLAttribute} attribute Attribute to process
  130. * @return {Integer} Index of the processed accessor on the "accessors" array
  131. */
  132. function processAccessor ( attribute ) {
  133. if ( !outputJSON.accessors ) {
  134. outputJSON.accessors = [];
  135. }
  136. var types = [
  137. 'SCALAR',
  138. 'VEC2',
  139. 'VEC3',
  140. 'VEC4'
  141. ];
  142. var componentType;
  143. // Detect the component type of the attribute array (float, uint or ushort)
  144. if ( attribute.array.constructor === Float32Array ) {
  145. componentType = gl.FLOAT;
  146. } else if ( attribute.array.constructor === Uint32Array ) {
  147. componentType = gl.UNSIGNED_INT;
  148. } else if ( attribute.array.constructor === Uint16Array ) {
  149. componentType = gl.UNSIGNED_SHORT;
  150. } else {
  151. throw new Error( 'THREE.GLTFExporter: Unsupported bufferAttribute component type.' );
  152. }
  153. var minMax = getMinMax( attribute );
  154. var bufferView = processBufferView( attribute, componentType );
  155. var gltfAccessor = {
  156. bufferView: bufferView.id,
  157. byteOffset: bufferView.byteOffset,
  158. componentType: componentType,
  159. count: attribute.count,
  160. max: minMax.max,
  161. min: minMax.min,
  162. type: types[ attribute.itemSize - 1 ]
  163. };
  164. outputJSON.accessors.push( gltfAccessor );
  165. return outputJSON.accessors.length - 1;
  166. }
  167. /**
  168. * Process image
  169. * @param {Texture} map Texture to process
  170. * @return {Integer} Index of the processed texture in the "images" array
  171. */
  172. function processImage ( map ) {
  173. if ( !outputJSON.images ) {
  174. outputJSON.images = [];
  175. }
  176. var gltfImage = {};
  177. if ( options.embedImages ) {
  178. // @TODO { bufferView, mimeType }
  179. } else {
  180. // @TODO base64 based on options
  181. gltfImage.uri = map.image.src;
  182. }
  183. outputJSON.images.push( gltfImage );
  184. return outputJSON.images.length - 1;
  185. }
  186. /**
  187. * Process sampler
  188. * @param {Texture} map Texture to process
  189. * @return {Integer} Index of the processed texture in the "samplers" array
  190. */
  191. function processSampler ( map ) {
  192. if ( !outputJSON.samplers ) {
  193. outputJSON.samplers = [];
  194. }
  195. var gltfSampler = {
  196. magFilter: glUtils.convert( map.magFilter ),
  197. minFilter: glUtils.convert( map.minFilter ),
  198. wrapS: glUtils.convert( map.wrapS ),
  199. wrapT: glUtils.convert( map.wrapT )
  200. };
  201. outputJSON.samplers.push( gltfSampler );
  202. return outputJSON.samplers.length - 1;
  203. }
  204. /**
  205. * Process texture
  206. * @param {Texture} map Map to process
  207. * @return {Integer} Index of the processed texture in the "textures" array
  208. */
  209. function processTexture ( map ) {
  210. if (!outputJSON.textures) {
  211. outputJSON.textures = [];
  212. }
  213. var gltfTexture = {
  214. sampler: processSampler( map ),
  215. source: processImage( map )
  216. };
  217. outputJSON.textures.push( gltfTexture );
  218. return outputJSON.textures.length - 1;
  219. }
  220. /**
  221. * Process material
  222. * @param {THREE.Material} material Material to process
  223. * @return {Integer} Index of the processed material in the "materials" array
  224. */
  225. function processMaterial ( material ) {
  226. if ( !outputJSON.materials ) {
  227. outputJSON.materials = [];
  228. }
  229. if ( !( material instanceof THREE.MeshStandardMaterial ) ) {
  230. console.warn( 'Currently just THREE.StandardMaterial is supported. Material conversion may lose information.' );
  231. }
  232. // @QUESTION Should we avoid including any attribute that has the default value?
  233. var gltfMaterial = {
  234. pbrMetallicRoughness: {}
  235. };
  236. // pbrMetallicRoughness.baseColorFactor
  237. var color = material.color.toArray().concat( [ material.opacity ] );
  238. if ( !equalArray( color, [ 1, 1, 1, 1 ] ) ) {
  239. gltfMaterial.pbrMetallicRoughness.baseColorFactor = color;
  240. }
  241. if ( material instanceof THREE.MeshStandardMaterial ) {
  242. gltfMaterial.pbrMetallicRoughness.metallicFactor = material.metalness;
  243. gltfMaterial.pbrMetallicRoughness.roughnessFactor = material.roughness;
  244. } else {
  245. gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.5;
  246. gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.5;
  247. }
  248. // pbrMetallicRoughness.baseColorTexture
  249. if ( material.map ) {
  250. gltfMaterial.pbrMetallicRoughness.baseColorTexture = {
  251. index: processTexture( material.map ),
  252. texCoord: 0 // @FIXME
  253. };
  254. }
  255. if ( material instanceof THREE.MeshBasicMaterial ||
  256. material instanceof THREE.LineBasicMaterial ||
  257. material instanceof THREE.PointsMaterial ) {
  258. } else {
  259. // emissiveFactor
  260. var emissive = material.emissive.clone().multiplyScalar( material.emissiveIntensity ).toArray();
  261. if ( !equalArray( emissive, [ 0, 0, 0 ] ) ) {
  262. gltfMaterial.emissiveFactor = emissive;
  263. }
  264. // emissiveTexture
  265. if ( material.emissiveMap ) {
  266. gltfMaterial.emissiveTexture = {
  267. index: processTexture( material.emissiveMap ),
  268. texCoord: 0 // @FIXME
  269. };
  270. }
  271. }
  272. // normalTexture
  273. if ( material.normalMap ) {
  274. gltfMaterial.normalTexture = {
  275. index: processTexture( material.normalMap ),
  276. texCoord: 0 // @FIXME
  277. };
  278. }
  279. // occlusionTexture
  280. if ( material.aoMap ) {
  281. gltfMaterial.occlusionTexture = {
  282. index: processTexture( material.aoMap ),
  283. texCoord: 0 // @FIXME
  284. };
  285. }
  286. // alphaMode
  287. if ( material.transparent ) {
  288. gltfMaterial.alphaMode = 'BLEND'; // @FIXME We should detect MASK or BLEND
  289. }
  290. // doubleSided
  291. if ( material.side === THREE.DoubleSide ) {
  292. gltfMaterial.doubleSided = true;
  293. }
  294. if ( material.name ) {
  295. gltfMaterial.name = material.name;
  296. }
  297. outputJSON.materials.push( gltfMaterial );
  298. return outputJSON.materials.length - 1;
  299. }
  300. /**
  301. * Process mesh
  302. * @param {THREE.Mesh} mesh Mesh to process
  303. * @return {Integer} Index of the processed mesh in the "meshes" array
  304. */
  305. function processMesh( mesh ) {
  306. if ( !outputJSON.meshes ) {
  307. outputJSON.meshes = [];
  308. }
  309. var geometry = mesh.geometry;
  310. // Use the correct mode
  311. if ( mesh instanceof THREE.LineSegments ) {
  312. mode = gl.LINES;
  313. } else if ( mesh instanceof THREE.LineLoop ) {
  314. mode = gl.LINE_LOOP;
  315. } else if ( mesh instanceof THREE.Line ) {
  316. mode = gl.LINE_STRIP;
  317. } else if ( mesh instanceof THREE.Points ) {
  318. mode = gl.POINTS;
  319. } else {
  320. if ( !( geometry instanceof THREE.BufferGeometry) ) {
  321. var geometryTemp = new THREE.BufferGeometry();
  322. geometryTemp.fromGeometry( geometry );
  323. geometry = geometryTemp;
  324. }
  325. if ( mesh.drawMode === THREE.TriangleFanDrawMode ) {
  326. console.warn( 'GLTFExporter: TriangleFanDrawMode and wireframe incompatible.' );
  327. mode = gl.TRIANGLE_FAN;
  328. } else if ( mesh.drawMode === THREE.TriangleStripDrawMode ) {
  329. mode = mesh.material.wireframe ? gl.LINE_STRIP : gl.TRIANGLE_STRIP;
  330. } else {
  331. mode = mesh.material.wireframe ? gl.LINES : gl.TRIANGLES;
  332. }
  333. }
  334. var gltfMesh = {
  335. primitives: [
  336. {
  337. mode: mode,
  338. attributes: {},
  339. material: processMaterial( mesh.material )
  340. }
  341. ]
  342. };
  343. if ( geometry.index ) {
  344. gltfMesh.primitives[ 0 ].indices = processAccessor( geometry.index );
  345. }
  346. // We've just one primitive per mesh
  347. var gltfAttributes = gltfMesh.primitives[ 0 ].attributes;
  348. var attributes = geometry.attributes;
  349. // Conversion between attributes names in threejs and gltf spec
  350. var nameConversion = {
  351. uv: 'TEXCOORD_0',
  352. uv2: 'TEXCOORD_1',
  353. color: 'COLOR_0',
  354. skinWeight: 'WEIGHTS_0',
  355. skinIndex: 'JOINTS_0'
  356. };
  357. // @QUESTION Detect if .vertexColors = THREE.VertexColors?
  358. // For every attribute create an accessor
  359. for ( var attributeName in geometry.attributes ) {
  360. var attribute = geometry.attributes[ attributeName ];
  361. attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
  362. gltfAttributes[ attributeName ] = processAccessor( attribute );
  363. }
  364. outputJSON.meshes.push( gltfMesh );
  365. return outputJSON.meshes.length - 1;
  366. }
  367. /**
  368. * Process camera
  369. * @param {THREE.Camera} camera Camera to process
  370. * @return {Integer} Index of the processed mesh in the "camera" array
  371. */
  372. function processCamera( camera ) {
  373. if ( !outputJSON.cameras ) {
  374. outputJSON.cameras = [];
  375. }
  376. var isOrtho = camera instanceof THREE.OrthographicCamera;
  377. var gltfCamera = {
  378. type: isOrtho ? 'orthographic' : 'perspective'
  379. };
  380. if ( isOrtho ) {
  381. gltfCamera.orthographic = {
  382. xmag: camera.right * 2,
  383. ymag: camera.top * 2,
  384. zfar: camera.far,
  385. znear: camera.near
  386. };
  387. } else {
  388. gltfCamera.perspective = {
  389. aspectRatio: camera.aspect,
  390. yfov: THREE.Math.degToRad( camera.fov ) / camera.aspect,
  391. zfar: camera.far,
  392. znear: camera.near
  393. };
  394. }
  395. if ( camera.name ) {
  396. gltfCamera.name = camera.type;
  397. }
  398. outputJSON.cameras.push( gltfCamera );
  399. return outputJSON.cameras.length - 1;
  400. }
  401. /**
  402. * Process Object3D node
  403. * @param {THREE.Object3D} node Object3D to processNode
  404. * @return {Integer} Index of the node in the nodes list
  405. */
  406. function processNode ( object ) {
  407. if ( !outputJSON.nodes ) {
  408. outputJSON.nodes = [];
  409. }
  410. var gltfNode = {};
  411. if ( options.trs ) {
  412. var rotation = object.quaternion.toArray();
  413. var position = object.position.toArray();
  414. var scale = object.scale.toArray();
  415. if ( !equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
  416. gltfNode.rotation = rotation;
  417. }
  418. if ( !equalArray( position, [ 0, 0, 0 ] ) ) {
  419. gltfNode.position = position;
  420. }
  421. if ( !equalArray( scale, [ 1, 1, 1 ] ) ) {
  422. gltfNode.scale = scale;
  423. }
  424. } else {
  425. object.updateMatrix();
  426. if (! equalArray( object.matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] ) ) {
  427. gltfNode.matrix = object.matrix.elements;
  428. }
  429. }
  430. if ( object.name ) {
  431. gltfNode.name = object.name;
  432. }
  433. if ( object.userData && Object.keys( object.userData ).length > 0 ) {
  434. try {
  435. gltfNode.extras = JSON.parse( JSON.stringify( object.userData ) );
  436. } catch (e) {
  437. throw new Error( 'GLTFExporter: userData can\'t be serialized' );
  438. }
  439. }
  440. if ( object instanceof THREE.Mesh ||
  441. object instanceof THREE.Line ||
  442. object instanceof THREE.Points ) {
  443. gltfNode.mesh = processMesh( object );
  444. } else if ( object instanceof THREE.Camera ) {
  445. gltfNode.camera = processCamera( object );
  446. }
  447. if ( object.children.length > 0 ) {
  448. gltfNode.children = [];
  449. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  450. var child = object.children[ i ];
  451. if ( child instanceof THREE.Mesh ||
  452. child instanceof THREE.Camera ||
  453. child instanceof THREE.Group ||
  454. child instanceof THREE.Line ||
  455. child instanceof THREE.Points) {
  456. gltfNode.children.push( processNode( child ) );
  457. }
  458. }
  459. }
  460. outputJSON.nodes.push( gltfNode );
  461. return outputJSON.nodes.length - 1;
  462. }
  463. /**
  464. * Process Scene
  465. * @param {THREE.Scene} node Scene to process
  466. */
  467. function processScene( scene ) {
  468. if ( !outputJSON.scenes ) {
  469. outputJSON.scenes = [];
  470. outputJSON.scene = 0;
  471. }
  472. var gltfScene = {
  473. nodes: []
  474. };
  475. if ( scene.name ) {
  476. gltfScene.name = scene.name;
  477. }
  478. outputJSON.scenes.push( gltfScene );
  479. for ( var i = 0, l = scene.children.length; i < l; i ++ ) {
  480. var child = scene.children[ i ];
  481. // @TODO We don't process lights yet
  482. if ( child instanceof THREE.Mesh ||
  483. child instanceof THREE.Camera ||
  484. child instanceof THREE.Group ||
  485. child instanceof THREE.Line ||
  486. child instanceof THREE.Points) {
  487. gltfScene.nodes.push( processNode( child ) );
  488. }
  489. }
  490. }
  491. /**
  492. * Creates a THREE.Scene to hold a list of objects and parse it
  493. * @param {Array} objects List of objects to process
  494. */
  495. function processObjects ( objects ) {
  496. var scene = new THREE.Scene();
  497. scene.name = 'AuxScene';
  498. for ( var i = 0; i < objects.length; i++ ) {
  499. // We push directly to children instead of calling `add` to prevent
  500. // modify the .parent and break its original scene and hierarchy
  501. scene.children.push( objects[ i ] );
  502. }
  503. processScene( scene );
  504. }
  505. function processInput( input ) {
  506. input = input instanceof Array ? input : [ input ];
  507. var objectsWithoutScene = [];
  508. for ( i = 0; i < input.length; i++ ) {
  509. if ( input[ i ] instanceof THREE.Scene ) {
  510. processScene( input[ i ] );
  511. } else {
  512. objectsWithoutScene.push( input[ i ] );
  513. }
  514. }
  515. if ( objectsWithoutScene.length > 0 ) {
  516. processObjects( objectsWithoutScene );
  517. }
  518. }
  519. processInput( input );
  520. // Generate buffer
  521. // Create a new blob with all the dataviews from the buffers
  522. var blob = new Blob( dataViews, { type: 'application/octet-binary' } );
  523. // Update the bytlength of the only main buffer and update the uri with the base64 representation of it
  524. if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) {
  525. outputJSON.buffers[ 0 ].byteLength = blob.size;
  526. objectURL = URL.createObjectURL( blob );
  527. var reader = new window.FileReader();
  528. reader.readAsDataURL( blob );
  529. reader.onloadend = function() {
  530. base64data = reader.result;
  531. outputJSON.buffers[ 0 ].uri = base64data;
  532. onDone( outputJSON );
  533. };
  534. } else {
  535. onDone ( outputJSON );
  536. }
  537. }
  538. };