GLTFExporter.js 39 KB

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