GLTFExporter.js 21 KB

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