GLTFExporter.js 42 KB

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