GLTFExporter.js 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354
  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 ] !== undefined ) {
  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 ] !== undefined ) {
  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. var weights = [];
  499. gltfMesh.primitives[ 0 ].targets = [];
  500. for ( var i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {
  501. var target = {};
  502. for ( var attributeName in geometry.morphAttributes ) {
  503. var attribute = geometry.morphAttributes[ attributeName ][ i ];
  504. attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
  505. target[ attributeName ] = processAccessor( attribute, geometry );
  506. }
  507. gltfMesh.primitives[ 0 ].targets.push( target );
  508. weights.push( mesh.morphTargetInfluences[ i ] );
  509. }
  510. gltfMesh.weights = weights;
  511. }
  512. outputJSON.meshes.push( gltfMesh );
  513. return outputJSON.meshes.length - 1;
  514. }
  515. /**
  516. * Process camera
  517. * @param {THREE.Camera} camera Camera to process
  518. * @return {Integer} Index of the processed mesh in the "camera" array
  519. */
  520. function processCamera( camera ) {
  521. if ( ! outputJSON.cameras ) {
  522. outputJSON.cameras = [];
  523. }
  524. var isOrtho = camera instanceof THREE.OrthographicCamera;
  525. var gltfCamera = {
  526. type: isOrtho ? 'orthographic' : 'perspective'
  527. };
  528. if ( isOrtho ) {
  529. gltfCamera.orthographic = {
  530. xmag: camera.right * 2,
  531. ymag: camera.top * 2,
  532. zfar: camera.far,
  533. znear: camera.near
  534. };
  535. } else {
  536. gltfCamera.perspective = {
  537. aspectRatio: camera.aspect,
  538. yfov: THREE.Math.degToRad( camera.fov ) / camera.aspect,
  539. zfar: camera.far,
  540. znear: camera.near
  541. };
  542. }
  543. if ( camera.name ) {
  544. gltfCamera.name = camera.type;
  545. }
  546. outputJSON.cameras.push( gltfCamera );
  547. return outputJSON.cameras.length - 1;
  548. }
  549. /**
  550. * Creates glTF animation entry from AnimationClip object.
  551. *
  552. * Status:
  553. * - Only properties listed in PATH_PROPERTIES may be animated.
  554. * - Only LINEAR and STEP interpolation currently supported.
  555. *
  556. * @param {THREE.AnimationClip} clip
  557. * @param {THREE.Object3D} root
  558. * @return {number}
  559. */
  560. function processAnimation ( clip, root ) {
  561. if ( ! outputJSON.animations ) {
  562. outputJSON.animations = [];
  563. }
  564. var channels = [];
  565. var samplers = [];
  566. for ( var i = 0; i < clip.tracks.length; ++ i ) {
  567. var track = clip.tracks[ i ];
  568. var trackBinding = THREE.PropertyBinding.parseTrackName( track.name );
  569. var trackNode = THREE.PropertyBinding.findNode( root, trackBinding.nodeName );
  570. var trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];
  571. if ( trackBinding.objectName === 'bones' ) {
  572. if ( trackNode.isSkinnedMesh === true ) {
  573. trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );
  574. } else {
  575. trackNode = undefined;
  576. }
  577. }
  578. if ( ! trackNode || ! trackProperty ) {
  579. console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
  580. return null;
  581. }
  582. var inputItemSize = 1;
  583. var outputItemSize = track.values.length / track.times.length;
  584. if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {
  585. outputItemSize /= trackNode.morphTargetInfluences.length;
  586. }
  587. samplers.push( {
  588. input: processAccessor( new THREE.BufferAttribute( track.times, inputItemSize ) ),
  589. output: processAccessor( new THREE.BufferAttribute( track.values, outputItemSize ) ),
  590. interpolation: track.getInterpolation() === THREE.InterpolateDiscrete ? 'STEP' : 'LINEAR'
  591. } );
  592. channels.push( {
  593. sampler: samplers.length - 1,
  594. target: {
  595. node: nodeMap[ trackNode.uuid ],
  596. path: trackProperty
  597. }
  598. } );
  599. }
  600. outputJSON.animations.push( {
  601. name: clip.name || 'clip_' + outputJSON.animations.length,
  602. samplers: samplers,
  603. channels: channels
  604. } );
  605. return outputJSON.animations.length - 1;
  606. }
  607. function processSkin( object ) {
  608. var node = outputJSON.nodes[ nodeMap[ object.uuid ] ];
  609. var skeleton = object.skeleton;
  610. var rootJoint = object.skeleton.bones[ 0 ];
  611. if ( rootJoint === undefined ) return null;
  612. var joints = [];
  613. var inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );
  614. for ( var i = 0; i < skeleton.bones.length; ++ i ) {
  615. joints.push( nodeMap[ skeleton.bones[ i ].uuid ] );
  616. skeleton.boneInverses[ i ].toArray( inverseBindMatrices, i * 16 );
  617. }
  618. if ( outputJSON.skins === undefined ) {
  619. outputJSON.skins = [];
  620. }
  621. outputJSON.skins.push( {
  622. inverseBindMatrices: processAccessor( new THREE.BufferAttribute( inverseBindMatrices, 16 ) ),
  623. joints: joints,
  624. skeleton: nodeMap[ rootJoint.uuid ]
  625. } );
  626. var skinIndex = node.skin = outputJSON.skins.length - 1;
  627. return skinIndex;
  628. }
  629. /**
  630. * Process Object3D node
  631. * @param {THREE.Object3D} node Object3D to processNode
  632. * @return {Integer} Index of the node in the nodes list
  633. */
  634. function processNode( object ) {
  635. if ( object instanceof THREE.Light ) {
  636. console.warn( 'GLTFExporter: Unsupported node type:', object.constructor.name );
  637. return null;
  638. }
  639. if ( ! outputJSON.nodes ) {
  640. outputJSON.nodes = [];
  641. }
  642. var gltfNode = {};
  643. if ( options.trs ) {
  644. var rotation = object.quaternion.toArray();
  645. var position = object.position.toArray();
  646. var scale = object.scale.toArray();
  647. if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
  648. gltfNode.rotation = rotation;
  649. }
  650. if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
  651. gltfNode.translation = position;
  652. }
  653. if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
  654. gltfNode.scale = scale;
  655. }
  656. } else {
  657. object.updateMatrix();
  658. if ( ! equalArray( object.matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] ) ) {
  659. gltfNode.matrix = object.matrix.elements;
  660. }
  661. }
  662. if ( object.name ) {
  663. gltfNode.name = object.name;
  664. }
  665. if ( object.userData && Object.keys( object.userData ).length > 0 ) {
  666. try {
  667. gltfNode.extras = JSON.parse( JSON.stringify( object.userData ) );
  668. } catch ( e ) {
  669. throw new Error( 'THREE.GLTFExporter: userData can\'t be serialized' );
  670. }
  671. }
  672. if ( object instanceof THREE.Mesh ||
  673. object instanceof THREE.Line ||
  674. object instanceof THREE.Points ) {
  675. gltfNode.mesh = processMesh( object );
  676. } else if ( object instanceof THREE.Camera ) {
  677. gltfNode.camera = processCamera( object );
  678. }
  679. if ( object instanceof THREE.SkinnedMesh ) {
  680. skins.push( object );
  681. }
  682. if ( object.children.length > 0 ) {
  683. var children = [];
  684. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  685. var child = object.children[ i ];
  686. if ( child.visible || options.onlyVisible === false ) {
  687. var node = processNode( child );
  688. if ( node !== null ) {
  689. children.push( node );
  690. }
  691. }
  692. }
  693. if ( children.length > 0 ) {
  694. gltfNode.children = children;
  695. }
  696. }
  697. outputJSON.nodes.push( gltfNode );
  698. var nodeIndex = nodeMap[ object.uuid ] = outputJSON.nodes.length - 1;
  699. return nodeIndex;
  700. }
  701. /**
  702. * Process Scene
  703. * @param {THREE.Scene} node Scene to process
  704. */
  705. function processScene( scene ) {
  706. if ( ! outputJSON.scenes ) {
  707. outputJSON.scenes = [];
  708. outputJSON.scene = 0;
  709. }
  710. var gltfScene = {
  711. nodes: []
  712. };
  713. if ( scene.name ) {
  714. gltfScene.name = scene.name;
  715. }
  716. outputJSON.scenes.push( gltfScene );
  717. var nodes = [];
  718. for ( var i = 0, l = scene.children.length; i < l; i ++ ) {
  719. var child = scene.children[ i ];
  720. if ( child.visible || options.onlyVisible === false ) {
  721. var node = processNode( child );
  722. if ( node !== null ) {
  723. nodes.push( node );
  724. }
  725. }
  726. }
  727. if ( nodes.length > 0 ) {
  728. gltfScene.nodes = nodes;
  729. }
  730. }
  731. /**
  732. * Creates a THREE.Scene to hold a list of objects and parse it
  733. * @param {Array} objects List of objects to process
  734. */
  735. function processObjects( objects ) {
  736. var scene = new THREE.Scene();
  737. scene.name = 'AuxScene';
  738. for ( var i = 0; i < objects.length; i ++ ) {
  739. // We push directly to children instead of calling `add` to prevent
  740. // modify the .parent and break its original scene and hierarchy
  741. scene.children.push( objects[ i ] );
  742. }
  743. processScene( scene );
  744. }
  745. function processInput( input ) {
  746. input = input instanceof Array ? input : [ input ];
  747. var objectsWithoutScene = [];
  748. for ( var i = 0; i < input.length; i ++ ) {
  749. if ( input[ i ] instanceof THREE.Scene ) {
  750. processScene( input[ i ] );
  751. } else {
  752. objectsWithoutScene.push( input[ i ] );
  753. }
  754. }
  755. if ( objectsWithoutScene.length > 0 ) {
  756. processObjects( objectsWithoutScene );
  757. }
  758. for ( var i = 0; i < skins.length; ++ i ) {
  759. processSkin( skins[ i ] );
  760. }
  761. for ( var i = 0; i < options.animations.length; ++ i ) {
  762. processAnimation( options.animations[ i ], input[ 0 ] );
  763. }
  764. }
  765. processInput( input );
  766. // Generate buffer
  767. // Create a new blob with all the dataviews from the buffers
  768. var blob = new Blob( dataViews, { type: 'application/octet-stream' } );
  769. // Update the bytlength of the only main buffer and update the uri with the base64 representation of it
  770. if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) {
  771. outputJSON.buffers[ 0 ].byteLength = blob.size;
  772. var reader = new window.FileReader();
  773. if ( options.binary === true ) {
  774. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
  775. var GLB_HEADER_BYTES = 12;
  776. var GLB_HEADER_MAGIC = 0x46546C67;
  777. var GLB_VERSION = 2;
  778. var GLB_CHUNK_PREFIX_BYTES = 8;
  779. var GLB_CHUNK_TYPE_JSON = 0x4E4F534A;
  780. var GLB_CHUNK_TYPE_BIN = 0x004E4942;
  781. reader.readAsArrayBuffer( blob );
  782. reader.onloadend = function () {
  783. // Binary chunk.
  784. var binaryChunk = reader.result;
  785. var binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  786. binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true );
  787. binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true );
  788. // JSON chunk.
  789. delete outputJSON.buffers[ 0 ].uri; // Omitted URI indicates use of binary chunk.
  790. var jsonChunk = stringToArrayBuffer( JSON.stringify( outputJSON ) );
  791. var jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  792. jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true );
  793. jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true );
  794. // GLB header.
  795. var header = new ArrayBuffer( GLB_HEADER_BYTES );
  796. var headerView = new DataView( header );
  797. headerView.setUint32( 0, GLB_HEADER_MAGIC, true );
  798. headerView.setUint32( 4, GLB_VERSION, true );
  799. var totalByteLength = GLB_HEADER_BYTES
  800. + jsonChunkPrefix.byteLength + jsonChunk.byteLength
  801. + binaryChunkPrefix.byteLength + binaryChunk.byteLength;
  802. headerView.setUint32( 8, totalByteLength, true );
  803. var glbBlob = new Blob( [
  804. header,
  805. jsonChunkPrefix,
  806. jsonChunk,
  807. binaryChunkPrefix,
  808. binaryChunk
  809. ], { type: 'application/octet-stream' } );
  810. var glbReader = new window.FileReader();
  811. glbReader.readAsArrayBuffer( glbBlob );
  812. glbReader.onloadend = function () {
  813. onDone( glbReader.result );
  814. };
  815. };
  816. } else {
  817. reader.readAsDataURL( blob );
  818. reader.onloadend = function () {
  819. var base64data = reader.result;
  820. outputJSON.buffers[ 0 ].uri = base64data;
  821. onDone( outputJSON );
  822. };
  823. }
  824. } else {
  825. onDone( outputJSON );
  826. }
  827. }
  828. };