2
0

GLTFExporter.js 28 KB

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