GLTFExporter.js 40 KB

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