GLTFExporter.js 35 KB

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