GLTFExporter.js 34 KB

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