GLTFExporter.js 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823
  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 forceIndices = options.forceIndices;
  739. var isMultiMaterial = Array.isArray( mesh.material );
  740. if ( isMultiMaterial && mesh.geometry.groups.length === 0 ) return null;
  741. if ( ! forceIndices && geometry.index === null && isMultiMaterial ) {
  742. // temporal workaround.
  743. console.warn( 'THREE.GLTFExporter: Creating index for non-indexed multi-material mesh.' );
  744. forceIndices = true;
  745. }
  746. var didForceIndices = false;
  747. if ( geometry.index === null && forceIndices ) {
  748. var indices = [];
  749. for ( var i = 0, il = geometry.attributes.position.count; i < il; i ++ ) {
  750. indices[ i ] = i;
  751. }
  752. geometry.setIndex( indices );
  753. didForceIndices = true;
  754. }
  755. var materials = isMultiMaterial ? mesh.material : [ mesh.material ];
  756. var groups = isMultiMaterial ? mesh.geometry.groups : [ { materialIndex: 0, start: undefined, count: undefined } ];
  757. for ( var i = 0, il = groups.length; i < il; i ++ ) {
  758. var primitive = {
  759. mode: mode,
  760. attributes: attributes,
  761. };
  762. if ( targets.length > 0 ) primitive.targets = targets;
  763. if ( geometry.index !== null ) {
  764. primitive.indices = processAccessor( geometry.index, geometry, groups[ i ].start, groups[ i ].count );
  765. }
  766. var material = processMaterial( materials[ groups[ i ].materialIndex ] );
  767. if ( material !== null ) {
  768. primitive.material = material;
  769. }
  770. primitives.push( primitive );
  771. }
  772. if ( didForceIndices ) {
  773. geometry.setIndex( null );
  774. }
  775. gltfMesh.primitives = primitives;
  776. if ( ! outputJSON.meshes ) {
  777. outputJSON.meshes = [];
  778. }
  779. outputJSON.meshes.push( gltfMesh );
  780. return outputJSON.meshes.length - 1;
  781. }
  782. /**
  783. * Process camera
  784. * @param {THREE.Camera} camera Camera to process
  785. * @return {Integer} Index of the processed mesh in the "camera" array
  786. */
  787. function processCamera( camera ) {
  788. if ( ! outputJSON.cameras ) {
  789. outputJSON.cameras = [];
  790. }
  791. var isOrtho = camera.isOrthographicCamera;
  792. var gltfCamera = {
  793. type: isOrtho ? 'orthographic' : 'perspective'
  794. };
  795. if ( isOrtho ) {
  796. gltfCamera.orthographic = {
  797. xmag: camera.right * 2,
  798. ymag: camera.top * 2,
  799. zfar: camera.far <= 0 ? 0.001 : camera.far,
  800. znear: camera.near < 0 ? 0 : camera.near
  801. };
  802. } else {
  803. gltfCamera.perspective = {
  804. aspectRatio: camera.aspect,
  805. yfov: THREE.Math.degToRad( camera.fov ) / camera.aspect,
  806. zfar: camera.far <= 0 ? 0.001 : camera.far,
  807. znear: camera.near < 0 ? 0 : camera.near
  808. };
  809. }
  810. if ( camera.name !== '' ) {
  811. gltfCamera.name = camera.type;
  812. }
  813. outputJSON.cameras.push( gltfCamera );
  814. return outputJSON.cameras.length - 1;
  815. }
  816. /**
  817. * Creates glTF animation entry from AnimationClip object.
  818. *
  819. * Status:
  820. * - Only properties listed in PATH_PROPERTIES may be animated.
  821. *
  822. * @param {THREE.AnimationClip} clip
  823. * @param {THREE.Object3D} root
  824. * @return {number}
  825. */
  826. function processAnimation( clip, root ) {
  827. if ( ! outputJSON.animations ) {
  828. outputJSON.animations = [];
  829. }
  830. var channels = [];
  831. var samplers = [];
  832. for ( var i = 0; i < clip.tracks.length; ++ i ) {
  833. var track = clip.tracks[ i ];
  834. var trackBinding = THREE.PropertyBinding.parseTrackName( track.name );
  835. var trackNode = THREE.PropertyBinding.findNode( root, trackBinding.nodeName );
  836. var trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];
  837. if ( trackBinding.objectName === 'bones' ) {
  838. if ( trackNode.isSkinnedMesh === true ) {
  839. trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );
  840. } else {
  841. trackNode = undefined;
  842. }
  843. }
  844. if ( ! trackNode || ! trackProperty ) {
  845. console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
  846. return null;
  847. }
  848. var inputItemSize = 1;
  849. var outputItemSize = track.values.length / track.times.length;
  850. if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {
  851. outputItemSize /= trackNode.morphTargetInfluences.length;
  852. }
  853. var interpolation;
  854. // @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE
  855. // Detecting glTF cubic spline interpolant by checking factory method's special property
  856. // GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return
  857. // valid value from .getInterpolation().
  858. if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) {
  859. interpolation = 'CUBICSPLINE';
  860. // itemSize of CUBICSPLINE keyframe is 9
  861. // (VEC3 * 3: inTangent, splineVertex, and outTangent)
  862. // but needs to be stored as VEC3 so dividing by 3 here.
  863. outputItemSize /= 3;
  864. } else if ( track.getInterpolation() === THREE.InterpolateDiscrete ) {
  865. interpolation = 'STEP';
  866. } else {
  867. interpolation = 'LINEAR';
  868. }
  869. samplers.push( {
  870. input: processAccessor( new THREE.BufferAttribute( track.times, inputItemSize ) ),
  871. output: processAccessor( new THREE.BufferAttribute( track.values, outputItemSize ) ),
  872. interpolation: interpolation
  873. } );
  874. channels.push( {
  875. sampler: samplers.length - 1,
  876. target: {
  877. node: nodeMap.get( trackNode ),
  878. path: trackProperty
  879. }
  880. } );
  881. }
  882. outputJSON.animations.push( {
  883. name: clip.name || 'clip_' + outputJSON.animations.length,
  884. samplers: samplers,
  885. channels: channels
  886. } );
  887. return outputJSON.animations.length - 1;
  888. }
  889. function processSkin( object ) {
  890. var node = outputJSON.nodes[ nodeMap.get( object ) ];
  891. var skeleton = object.skeleton;
  892. var rootJoint = object.skeleton.bones[ 0 ];
  893. if ( rootJoint === undefined ) return null;
  894. var joints = [];
  895. var inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );
  896. for ( var i = 0; i < skeleton.bones.length; ++ i ) {
  897. joints.push( nodeMap.get( skeleton.bones[ i ] ) );
  898. skeleton.boneInverses[ i ].toArray( inverseBindMatrices, i * 16 );
  899. }
  900. if ( outputJSON.skins === undefined ) {
  901. outputJSON.skins = [];
  902. }
  903. outputJSON.skins.push( {
  904. inverseBindMatrices: processAccessor( new THREE.BufferAttribute( inverseBindMatrices, 16 ) ),
  905. joints: joints,
  906. skeleton: nodeMap.get( rootJoint )
  907. } );
  908. var skinIndex = node.skin = outputJSON.skins.length - 1;
  909. return skinIndex;
  910. }
  911. /**
  912. * Process Object3D node
  913. * @param {THREE.Object3D} node Object3D to processNode
  914. * @return {Integer} Index of the node in the nodes list
  915. */
  916. function processNode( object ) {
  917. if ( object.isLight ) {
  918. console.warn( 'GLTFExporter: Unsupported node type:', object.constructor.name );
  919. return null;
  920. }
  921. if ( ! outputJSON.nodes ) {
  922. outputJSON.nodes = [];
  923. }
  924. var gltfNode = {};
  925. if ( options.trs ) {
  926. var rotation = object.quaternion.toArray();
  927. var position = object.position.toArray();
  928. var scale = object.scale.toArray();
  929. if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
  930. gltfNode.rotation = rotation;
  931. }
  932. if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
  933. gltfNode.translation = position;
  934. }
  935. if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
  936. gltfNode.scale = scale;
  937. }
  938. } else {
  939. object.updateMatrix();
  940. if ( ! equalArray( object.matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] ) ) {
  941. gltfNode.matrix = object.matrix.elements;
  942. }
  943. }
  944. // We don't export empty strings name because it represents no-name in Three.js.
  945. if ( object.name !== '' ) {
  946. gltfNode.name = String( object.name );
  947. }
  948. if ( object.userData && Object.keys( object.userData ).length > 0 ) {
  949. gltfNode.extras = serializeUserData( object );
  950. }
  951. if ( object.isMesh || object.isLine || object.isPoints ) {
  952. var mesh = processMesh( object );
  953. if ( mesh !== null ) {
  954. gltfNode.mesh = mesh;
  955. }
  956. } else if ( object.isCamera ) {
  957. gltfNode.camera = processCamera( object );
  958. }
  959. if ( object.isSkinnedMesh ) {
  960. skins.push( object );
  961. }
  962. if ( object.children.length > 0 ) {
  963. var children = [];
  964. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  965. var child = object.children[ i ];
  966. if ( child.visible || options.onlyVisible === false ) {
  967. var node = processNode( child );
  968. if ( node !== null ) {
  969. children.push( node );
  970. }
  971. }
  972. }
  973. if ( children.length > 0 ) {
  974. gltfNode.children = children;
  975. }
  976. }
  977. outputJSON.nodes.push( gltfNode );
  978. var nodeIndex = outputJSON.nodes.length - 1;
  979. nodeMap.set( object, nodeIndex );
  980. return nodeIndex;
  981. }
  982. /**
  983. * Process Scene
  984. * @param {THREE.Scene} node Scene to process
  985. */
  986. function processScene( scene ) {
  987. if ( ! outputJSON.scenes ) {
  988. outputJSON.scenes = [];
  989. outputJSON.scene = 0;
  990. }
  991. var gltfScene = {
  992. nodes: []
  993. };
  994. if ( scene.name !== '' ) {
  995. gltfScene.name = scene.name;
  996. }
  997. outputJSON.scenes.push( gltfScene );
  998. var nodes = [];
  999. for ( var i = 0, l = scene.children.length; i < l; i ++ ) {
  1000. var child = scene.children[ i ];
  1001. if ( child.visible || options.onlyVisible === false ) {
  1002. var node = processNode( child );
  1003. if ( node !== null ) {
  1004. nodes.push( node );
  1005. }
  1006. }
  1007. }
  1008. if ( nodes.length > 0 ) {
  1009. gltfScene.nodes = nodes;
  1010. }
  1011. }
  1012. /**
  1013. * Creates a THREE.Scene to hold a list of objects and parse it
  1014. * @param {Array} objects List of objects to process
  1015. */
  1016. function processObjects( objects ) {
  1017. var scene = new THREE.Scene();
  1018. scene.name = 'AuxScene';
  1019. for ( var i = 0; i < objects.length; i ++ ) {
  1020. // We push directly to children instead of calling `add` to prevent
  1021. // modify the .parent and break its original scene and hierarchy
  1022. scene.children.push( objects[ i ] );
  1023. }
  1024. processScene( scene );
  1025. }
  1026. function processInput( input ) {
  1027. input = input instanceof Array ? input : [ input ];
  1028. var objectsWithoutScene = [];
  1029. for ( var i = 0; i < input.length; i ++ ) {
  1030. if ( input[ i ] instanceof THREE.Scene ) {
  1031. processScene( input[ i ] );
  1032. } else {
  1033. objectsWithoutScene.push( input[ i ] );
  1034. }
  1035. }
  1036. if ( objectsWithoutScene.length > 0 ) {
  1037. processObjects( objectsWithoutScene );
  1038. }
  1039. for ( var i = 0; i < skins.length; ++ i ) {
  1040. processSkin( skins[ i ] );
  1041. }
  1042. for ( var i = 0; i < options.animations.length; ++ i ) {
  1043. processAnimation( options.animations[ i ], input[ 0 ] );
  1044. }
  1045. }
  1046. processInput( input );
  1047. Promise.all( pending ).then( function () {
  1048. // Merge buffers.
  1049. var blob = new Blob( buffers, { type: 'application/octet-stream' } );
  1050. // Declare extensions.
  1051. var extensionsUsedList = Object.keys( extensionsUsed );
  1052. if ( extensionsUsedList.length > 0 ) outputJSON.extensionsUsed = extensionsUsedList;
  1053. if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) {
  1054. // Update bytelength of the single buffer.
  1055. outputJSON.buffers[ 0 ].byteLength = blob.size;
  1056. var reader = new window.FileReader();
  1057. if ( options.binary === true ) {
  1058. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
  1059. var GLB_HEADER_BYTES = 12;
  1060. var GLB_HEADER_MAGIC = 0x46546C67;
  1061. var GLB_VERSION = 2;
  1062. var GLB_CHUNK_PREFIX_BYTES = 8;
  1063. var GLB_CHUNK_TYPE_JSON = 0x4E4F534A;
  1064. var GLB_CHUNK_TYPE_BIN = 0x004E4942;
  1065. reader.readAsArrayBuffer( blob );
  1066. reader.onloadend = function () {
  1067. // Binary chunk.
  1068. var binaryChunk = getPaddedArrayBuffer( reader.result );
  1069. var binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  1070. binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true );
  1071. binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true );
  1072. // JSON chunk.
  1073. var jsonChunk = getPaddedArrayBuffer( stringToArrayBuffer( JSON.stringify( outputJSON ) ), 0x20 );
  1074. var jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  1075. jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true );
  1076. jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true );
  1077. // GLB header.
  1078. var header = new ArrayBuffer( GLB_HEADER_BYTES );
  1079. var headerView = new DataView( header );
  1080. headerView.setUint32( 0, GLB_HEADER_MAGIC, true );
  1081. headerView.setUint32( 4, GLB_VERSION, true );
  1082. var totalByteLength = GLB_HEADER_BYTES
  1083. + jsonChunkPrefix.byteLength + jsonChunk.byteLength
  1084. + binaryChunkPrefix.byteLength + binaryChunk.byteLength;
  1085. headerView.setUint32( 8, totalByteLength, true );
  1086. var glbBlob = new Blob( [
  1087. header,
  1088. jsonChunkPrefix,
  1089. jsonChunk,
  1090. binaryChunkPrefix,
  1091. binaryChunk
  1092. ], { type: 'application/octet-stream' } );
  1093. var glbReader = new window.FileReader();
  1094. glbReader.readAsArrayBuffer( glbBlob );
  1095. glbReader.onloadend = function () {
  1096. onDone( glbReader.result );
  1097. };
  1098. };
  1099. } else {
  1100. reader.readAsDataURL( blob );
  1101. reader.onloadend = function () {
  1102. var base64data = reader.result;
  1103. outputJSON.buffers[ 0 ].uri = base64data;
  1104. onDone( outputJSON );
  1105. };
  1106. }
  1107. } else {
  1108. onDone( outputJSON );
  1109. }
  1110. } );
  1111. }
  1112. };