GLTFExporter.js 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379
  1. /**
  2. * @author fernandojsg / http://fernandojsg.com
  3. */
  4. //------------------------------------------------------------------------------
  5. // Constants
  6. //------------------------------------------------------------------------------
  7. var WEBGL_CONSTANTS = {
  8. POINTS: 0x0000,
  9. LINES: 0x0001,
  10. LINE_LOOP: 0x0002,
  11. LINE_STRIP: 0x0003,
  12. TRIANGLES: 0x0004,
  13. TRIANGLE_STRIP: 0x0005,
  14. TRIANGLE_FAN: 0x0006,
  15. UNSIGNED_BYTE: 0x1401,
  16. UNSIGNED_SHORT: 0x1403,
  17. FLOAT: 0x1406,
  18. UNSIGNED_INT: 0x1405,
  19. ARRAY_BUFFER: 0x8892,
  20. ELEMENT_ARRAY_BUFFER: 0x8893,
  21. NEAREST: 0x2600,
  22. LINEAR: 0x2601,
  23. NEAREST_MIPMAP_NEAREST: 0x2700,
  24. LINEAR_MIPMAP_NEAREST: 0x2701,
  25. NEAREST_MIPMAP_LINEAR: 0x2702,
  26. LINEAR_MIPMAP_LINEAR: 0x2703
  27. };
  28. var THREE_TO_WEBGL = {
  29. // @TODO Replace with computed property name [THREE.*] when available on es6
  30. 1003: WEBGL_CONSTANTS.NEAREST,
  31. 1004: WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST,
  32. 1005: WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR,
  33. 1006: WEBGL_CONSTANTS.LINEAR,
  34. 1007: WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST,
  35. 1008: WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR
  36. };
  37. var PATH_PROPERTIES = {
  38. scale: 'scale',
  39. position: 'translation',
  40. quaternion: 'rotation',
  41. morphTargetInfluences: 'weights'
  42. };
  43. //------------------------------------------------------------------------------
  44. // GLTF Exporter
  45. //------------------------------------------------------------------------------
  46. THREE.GLTFExporter = function () {};
  47. THREE.GLTFExporter.prototype = {
  48. constructor: THREE.GLTFExporter,
  49. /**
  50. * Parse scenes and generate GLTF output
  51. * @param {THREE.Scene or [THREE.Scenes]} input THREE.Scene or Array of THREE.Scenes
  52. * @param {Function} onDone Callback on completed
  53. * @param {Object} options options
  54. */
  55. parse: function ( input, onDone, options ) {
  56. var DEFAULT_OPTIONS = {
  57. trs: false,
  58. onlyVisible: true,
  59. truncateDrawRange: true,
  60. embedImages: true,
  61. animations: []
  62. };
  63. options = Object.assign( {}, DEFAULT_OPTIONS, options );
  64. if ( options.animations.length > 0 ) {
  65. // Only TRS properties, and not matrices, may be targeted by animation.
  66. options.trs = true;
  67. }
  68. var outputJSON = {
  69. asset: {
  70. version: "2.0",
  71. generator: "THREE.GLTFExporter"
  72. }
  73. };
  74. var byteOffset = 0;
  75. var dataViews = [];
  76. var nodeMap = {};
  77. var skins = [];
  78. var cachedData = {
  79. images: {},
  80. materials: {}
  81. };
  82. var cachedCanvas;
  83. /**
  84. * Compare two arrays
  85. */
  86. /**
  87. * Compare two arrays
  88. * @param {Array} array1 Array 1 to compare
  89. * @param {Array} array2 Array 2 to compare
  90. * @return {Boolean} Returns true if both arrays are equal
  91. */
  92. function equalArray( array1, array2 ) {
  93. return ( array1.length === array2.length ) && array1.every( function ( element, index ) {
  94. return element === array2[ index ];
  95. } );
  96. }
  97. /**
  98. * Converts a string to an ArrayBuffer.
  99. * @param {string} text
  100. * @return {ArrayBuffer}
  101. */
  102. function stringToArrayBuffer( text ) {
  103. if ( window.TextEncoder !== undefined ) {
  104. return new TextEncoder().encode( text ).buffer;
  105. }
  106. var buffer = new ArrayBuffer( text.length );
  107. var bufferView = new Uint8Array( buffer );
  108. for ( var i = 0; i < text.length; ++ i ) {
  109. bufferView[ i ] = text.charCodeAt( i );
  110. }
  111. return buffer;
  112. }
  113. /**
  114. * Get the min and max vectors from the given attribute
  115. * @param {THREE.BufferAttribute} attribute Attribute to find the min/max
  116. * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
  117. */
  118. function getMinMax( attribute ) {
  119. var output = {
  120. min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
  121. max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
  122. };
  123. for ( var i = 0; i < attribute.count; i ++ ) {
  124. for ( var a = 0; a < attribute.itemSize; a ++ ) {
  125. var value = attribute.array[ i * attribute.itemSize + a ];
  126. output.min[ a ] = Math.min( output.min[ a ], value );
  127. output.max[ a ] = Math.max( output.max[ a ], value );
  128. }
  129. }
  130. return output;
  131. }
  132. /**
  133. * Get the required size + padding for a buffer, rounded to the next 4-byte boundary.
  134. * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
  135. *
  136. * @param {Integer} bufferSize The size the original buffer.
  137. * @returns {Integer} new buffer size with required padding.
  138. *
  139. */
  140. function getPaddedBufferSize( bufferSize ) {
  141. // adapted from https://github.com/AnalyticalGraphicsInc/obj2gltf/blob/master/lib/getBufferPadded.js
  142. var boundary = 4;
  143. var remainder = bufferSize % boundary;
  144. var padding = remainder === 0 ? 0 : boundary - remainder;
  145. return bufferSize + padding;
  146. }
  147. /**
  148. * Process a buffer to append to the default one.
  149. * @param {THREE.BufferAttribute} attribute Attribute to store
  150. * @param {Integer} componentType Component type (Unsigned short, unsigned int or float)
  151. * @return {Integer} Index of the buffer created (Currently always 0)
  152. */
  153. function processBuffer( attribute, componentType, start, count ) {
  154. if ( ! outputJSON.buffers ) {
  155. outputJSON.buffers = [
  156. {
  157. byteLength: 0,
  158. uri: ''
  159. }
  160. ];
  161. }
  162. var offset = 0;
  163. var componentSize = componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ? 2 : 4;
  164. // Create a new dataview and dump the attribute's array into it
  165. var byteLength = count * attribute.itemSize * componentSize;
  166. // adjust required size of array buffer with padding
  167. // to satisfy gltf requirement that the length is divisible by 4
  168. byteLength = getPaddedBufferSize( byteLength );
  169. var dataView = new DataView( new ArrayBuffer( byteLength ) );
  170. for ( var i = start; i < start + count; i ++ ) {
  171. for ( var a = 0; a < attribute.itemSize; a ++ ) {
  172. var value = attribute.array[ i * attribute.itemSize + a ];
  173. if ( componentType === WEBGL_CONSTANTS.FLOAT ) {
  174. dataView.setFloat32( offset, value, true );
  175. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_INT ) {
  176. dataView.setUint8( offset, value, true );
  177. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
  178. dataView.setUint16( offset, value, true );
  179. }
  180. offset += componentSize;
  181. }
  182. }
  183. // We just use one buffer
  184. dataViews.push( dataView );
  185. // Always using just one buffer
  186. return 0;
  187. }
  188. /**
  189. * Process and generate a BufferView
  190. * @param {THREE.BufferAttribute} data
  191. * @param {number} componentType
  192. * @param {number} start
  193. * @param {number} count
  194. * @param {number} target (Optional) Target usage of the BufferView
  195. * @return {Object}
  196. */
  197. function processBufferView( data, componentType, start, count, target ) {
  198. if ( ! outputJSON.bufferViews ) {
  199. outputJSON.bufferViews = [];
  200. }
  201. var componentSize = componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ? 2 : 4;
  202. // Create a new dataview and dump the attribute's array into it
  203. var byteLength = count * data.itemSize * componentSize;
  204. var gltfBufferView = {
  205. buffer: processBuffer( data, componentType, start, count ),
  206. byteOffset: byteOffset,
  207. byteLength: byteLength
  208. };
  209. if ( target !== undefined ) gltfBufferView.target = target;
  210. if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {
  211. // Only define byteStride for vertex attributes.
  212. gltfBufferView.byteStride = data.itemSize * componentSize;
  213. }
  214. byteOffset += byteLength;
  215. outputJSON.bufferViews.push( gltfBufferView );
  216. // @TODO Ideally we'll have just two bufferviews: 0 is for vertex attributes, 1 for indices
  217. var output = {
  218. id: outputJSON.bufferViews.length - 1,
  219. byteLength: 0
  220. };
  221. return output;
  222. }
  223. /**
  224. * Process attribute to generate an accessor
  225. * @param {THREE.BufferAttribute} attribute Attribute to process
  226. * @param {THREE.BufferGeometry} geometry (Optional) Geometry used for truncated draw range
  227. * @return {Integer} Index of the processed accessor on the "accessors" array
  228. */
  229. function processAccessor( attribute, geometry ) {
  230. if ( ! outputJSON.accessors ) {
  231. outputJSON.accessors = [];
  232. }
  233. var types = {
  234. 1: 'SCALAR',
  235. 2: 'VEC2',
  236. 3: 'VEC3',
  237. 4: 'VEC4',
  238. 16: 'MAT4'
  239. };
  240. var componentType;
  241. // Detect the component type of the attribute array (float, uint or ushort)
  242. if ( attribute.array.constructor === Float32Array ) {
  243. componentType = WEBGL_CONSTANTS.FLOAT;
  244. } else if ( attribute.array.constructor === Uint32Array ) {
  245. componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
  246. } else if ( attribute.array.constructor === Uint16Array ) {
  247. componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
  248. } else {
  249. throw new Error( 'THREE.GLTFExporter: Unsupported bufferAttribute component type.' );
  250. }
  251. var minMax = getMinMax( attribute );
  252. var start = 0;
  253. var count = attribute.count;
  254. // @TODO Indexed buffer geometry with drawRange not supported yet
  255. if ( options.truncateDrawRange && geometry !== undefined && geometry.index === null ) {
  256. start = geometry.drawRange.start;
  257. count = geometry.drawRange.count !== Infinity ? geometry.drawRange.count : attribute.count;
  258. }
  259. var bufferViewTarget;
  260. // If geometry isn't provided, don't infer the target usage of the bufferView. For
  261. // animation samplers, target must not be set.
  262. if ( geometry !== undefined ) {
  263. var isVertexAttributes = componentType === WEBGL_CONSTANTS.FLOAT;
  264. bufferViewTarget = isVertexAttributes ? WEBGL_CONSTANTS.ARRAY_BUFFER : WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER;
  265. }
  266. var bufferView = processBufferView( attribute, componentType, start, count, bufferViewTarget );
  267. var gltfAccessor = {
  268. bufferView: bufferView.id,
  269. byteOffset: bufferView.byteOffset,
  270. componentType: componentType,
  271. count: count,
  272. max: minMax.max,
  273. min: minMax.min,
  274. type: types[ attribute.itemSize ]
  275. };
  276. outputJSON.accessors.push( gltfAccessor );
  277. return outputJSON.accessors.length - 1;
  278. }
  279. /**
  280. * Process image
  281. * @param {Texture} map Texture to process
  282. * @return {Integer} Index of the processed texture in the "images" array
  283. */
  284. function processImage( map ) {
  285. if ( cachedData.images[ map.uuid ] !== undefined ) {
  286. return cachedData.images[ map.uuid ];
  287. }
  288. if ( ! outputJSON.images ) {
  289. outputJSON.images = [];
  290. }
  291. var mimeType = map.format === THREE.RGBAFormat ? 'image/png' : 'image/jpeg';
  292. var gltfImage = {mimeType: mimeType};
  293. if ( options.embedImages ) {
  294. var canvas = cachedCanvas = cachedCanvas || document.createElement( 'canvas' );
  295. canvas.width = map.image.width;
  296. canvas.height = map.image.height;
  297. var ctx = canvas.getContext( '2d' );
  298. if ( map.flipY === true ) {
  299. ctx.translate( 0, map.image.height );
  300. ctx.scale( 1, -1 );
  301. }
  302. ctx.drawImage( map.image, 0, 0 );
  303. // @TODO Embed in { bufferView } if options.binary set.
  304. gltfImage.uri = canvas.toDataURL( mimeType );
  305. } else {
  306. gltfImage.uri = map.image.src;
  307. }
  308. outputJSON.images.push( gltfImage );
  309. var index = outputJSON.images.length - 1;
  310. cachedData.images[ map.uuid ] = index;
  311. return index;
  312. }
  313. /**
  314. * Process sampler
  315. * @param {Texture} map Texture to process
  316. * @return {Integer} Index of the processed texture in the "samplers" array
  317. */
  318. function processSampler( map ) {
  319. if ( ! outputJSON.samplers ) {
  320. outputJSON.samplers = [];
  321. }
  322. var gltfSampler = {
  323. magFilter: THREE_TO_WEBGL[ map.magFilter ],
  324. minFilter: THREE_TO_WEBGL[ map.minFilter ],
  325. wrapS: THREE_TO_WEBGL[ map.wrapS ],
  326. wrapT: THREE_TO_WEBGL[ map.wrapT ]
  327. };
  328. outputJSON.samplers.push( gltfSampler );
  329. return outputJSON.samplers.length - 1;
  330. }
  331. /**
  332. * Process texture
  333. * @param {Texture} map Map to process
  334. * @return {Integer} Index of the processed texture in the "textures" array
  335. */
  336. function processTexture( map ) {
  337. if ( ! outputJSON.textures ) {
  338. outputJSON.textures = [];
  339. }
  340. var gltfTexture = {
  341. sampler: processSampler( map ),
  342. source: processImage( map )
  343. };
  344. outputJSON.textures.push( gltfTexture );
  345. return outputJSON.textures.length - 1;
  346. }
  347. /**
  348. * Process material
  349. * @param {THREE.Material} material Material to process
  350. * @return {Integer} Index of the processed material in the "materials" array
  351. */
  352. function processMaterial( material ) {
  353. if ( cachedData.materials[ material.uuid ] !== undefined ) {
  354. return cachedData.materials[ material.uuid ];
  355. }
  356. if ( ! outputJSON.materials ) {
  357. outputJSON.materials = [];
  358. }
  359. if ( material instanceof THREE.ShaderMaterial ) {
  360. console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' );
  361. return null;
  362. }
  363. if ( ! ( material instanceof THREE.MeshStandardMaterial ) ) {
  364. console.warn( 'GLTFExporter: Currently just THREE.StandardMaterial is supported. Material conversion may lose information.' );
  365. }
  366. // @QUESTION Should we avoid including any attribute that has the default value?
  367. var gltfMaterial = {
  368. pbrMetallicRoughness: {}
  369. };
  370. // pbrMetallicRoughness.baseColorFactor
  371. var color = material.color.toArray().concat( [ material.opacity ] );
  372. if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) {
  373. gltfMaterial.pbrMetallicRoughness.baseColorFactor = color;
  374. }
  375. if ( material instanceof THREE.MeshStandardMaterial ) {
  376. gltfMaterial.pbrMetallicRoughness.metallicFactor = material.metalness;
  377. gltfMaterial.pbrMetallicRoughness.roughnessFactor = material.roughness;
  378. } else {
  379. gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.5;
  380. gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.5;
  381. }
  382. // pbrMetallicRoughness.baseColorTexture
  383. if ( material.map ) {
  384. gltfMaterial.pbrMetallicRoughness.baseColorTexture = {
  385. index: processTexture( material.map )
  386. };
  387. }
  388. if ( material instanceof THREE.MeshBasicMaterial ||
  389. material instanceof THREE.LineBasicMaterial ||
  390. material instanceof THREE.PointsMaterial ) {
  391. } else {
  392. // emissiveFactor
  393. var emissive = material.emissive.clone().multiplyScalar( material.emissiveIntensity ).toArray();
  394. if ( ! equalArray( emissive, [ 0, 0, 0 ] ) ) {
  395. gltfMaterial.emissiveFactor = emissive;
  396. }
  397. // emissiveTexture
  398. if ( material.emissiveMap ) {
  399. gltfMaterial.emissiveTexture = {
  400. index: processTexture( material.emissiveMap )
  401. };
  402. }
  403. }
  404. // normalTexture
  405. if ( material.normalMap ) {
  406. gltfMaterial.normalTexture = {
  407. index: processTexture( material.normalMap )
  408. };
  409. if ( material.normalScale.x !== - 1 ) {
  410. if ( material.normalScale.x !== material.normalScale.y ) {
  411. console.warn( 'THREE.GLTFExporter: Normal scale components are different, ignoring Y and exporting X.' );
  412. }
  413. gltfMaterial.normalTexture.scale = material.normalScale.x;
  414. }
  415. }
  416. // occlusionTexture
  417. if ( material.aoMap ) {
  418. gltfMaterial.occlusionTexture = {
  419. index: processTexture( material.aoMap )
  420. };
  421. if ( material.aoMapIntensity !== 1.0 ) {
  422. gltfMaterial.occlusionTexture.strength = material.aoMapIntensity;
  423. }
  424. }
  425. // alphaMode
  426. if ( material.transparent || material.alphaTest > 0.0 ) {
  427. gltfMaterial.alphaMode = material.opacity < 1.0 ? 'BLEND' : 'MASK';
  428. // Write alphaCutoff if it's non-zero and different from the default (0.5).
  429. if ( material.alphaTest > 0.0 && material.alphaTest !== 0.5 ) {
  430. gltfMaterial.alphaCutoff = material.alphaTest;
  431. }
  432. }
  433. // doubleSided
  434. if ( material.side === THREE.DoubleSide ) {
  435. gltfMaterial.doubleSided = true;
  436. }
  437. if ( material.name ) {
  438. gltfMaterial.name = material.name;
  439. }
  440. outputJSON.materials.push( gltfMaterial );
  441. var index = outputJSON.materials.length - 1;
  442. cachedData.materials[ material.uuid ] = index;
  443. return index;
  444. }
  445. /**
  446. * Process mesh
  447. * @param {THREE.Mesh} mesh Mesh to process
  448. * @return {Integer} Index of the processed mesh in the "meshes" array
  449. */
  450. function processMesh( mesh ) {
  451. if ( ! outputJSON.meshes ) {
  452. outputJSON.meshes = [];
  453. }
  454. var geometry = mesh.geometry;
  455. var mode;
  456. // Use the correct mode
  457. if ( mesh instanceof THREE.LineSegments ) {
  458. mode = WEBGL_CONSTANTS.LINES;
  459. } else if ( mesh instanceof THREE.LineLoop ) {
  460. mode = WEBGL_CONSTANTS.LINE_LOOP;
  461. } else if ( mesh instanceof THREE.Line ) {
  462. mode = WEBGL_CONSTANTS.LINE_STRIP;
  463. } else if ( mesh instanceof THREE.Points ) {
  464. mode = WEBGL_CONSTANTS.POINTS;
  465. } else {
  466. if ( ! geometry.isBufferGeometry ) {
  467. var geometryTemp = new THREE.BufferGeometry();
  468. geometryTemp.fromGeometry( geometry );
  469. geometry = geometryTemp;
  470. }
  471. if ( mesh.drawMode === THREE.TriangleFanDrawMode ) {
  472. console.warn( 'GLTFExporter: TriangleFanDrawMode and wireframe incompatible.' );
  473. mode = WEBGL_CONSTANTS.TRIANGLE_FAN;
  474. } else if ( mesh.drawMode === THREE.TriangleStripDrawMode ) {
  475. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINE_STRIP : WEBGL_CONSTANTS.TRIANGLE_STRIP;
  476. } else {
  477. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
  478. }
  479. }
  480. var gltfMesh = {
  481. primitives: [
  482. {
  483. mode: mode,
  484. attributes: {},
  485. }
  486. ]
  487. };
  488. var material = processMaterial( mesh.material );
  489. if ( material !== null ) {
  490. gltfMesh.primitives[ 0 ].material = material;
  491. }
  492. if ( geometry.index ) {
  493. gltfMesh.primitives[ 0 ].indices = processAccessor( geometry.index, geometry );
  494. }
  495. // We've just one primitive per mesh
  496. var gltfAttributes = gltfMesh.primitives[ 0 ].attributes;
  497. // Conversion between attributes names in threejs and gltf spec
  498. var nameConversion = {
  499. uv: 'TEXCOORD_0',
  500. uv2: 'TEXCOORD_1',
  501. color: 'COLOR_0',
  502. skinWeight: 'WEIGHTS_0',
  503. skinIndex: 'JOINTS_0'
  504. };
  505. // @QUESTION Detect if .vertexColors = THREE.VertexColors?
  506. // For every attribute create an accessor
  507. for ( var attributeName in geometry.attributes ) {
  508. var attribute = geometry.attributes[ attributeName ];
  509. attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
  510. if ( attributeName.substr( 0, 5 ) !== 'MORPH' ) {
  511. gltfAttributes[ attributeName ] = processAccessor( attribute, geometry );
  512. }
  513. }
  514. // Morph targets
  515. if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) {
  516. var weights = [];
  517. gltfMesh.primitives[ 0 ].targets = [];
  518. for ( var i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {
  519. var target = {};
  520. for ( var attributeName in geometry.morphAttributes ) {
  521. var attribute = geometry.morphAttributes[ attributeName ][ i ];
  522. attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
  523. target[ attributeName ] = processAccessor( attribute, geometry );
  524. }
  525. gltfMesh.primitives[ 0 ].targets.push( target );
  526. weights.push( mesh.morphTargetInfluences[ i ] );
  527. }
  528. gltfMesh.weights = weights;
  529. }
  530. outputJSON.meshes.push( gltfMesh );
  531. return outputJSON.meshes.length - 1;
  532. }
  533. /**
  534. * Process camera
  535. * @param {THREE.Camera} camera Camera to process
  536. * @return {Integer} Index of the processed mesh in the "camera" array
  537. */
  538. function processCamera( camera ) {
  539. if ( ! outputJSON.cameras ) {
  540. outputJSON.cameras = [];
  541. }
  542. var isOrtho = camera instanceof THREE.OrthographicCamera;
  543. var gltfCamera = {
  544. type: isOrtho ? 'orthographic' : 'perspective'
  545. };
  546. if ( isOrtho ) {
  547. gltfCamera.orthographic = {
  548. xmag: camera.right * 2,
  549. ymag: camera.top * 2,
  550. zfar: camera.far,
  551. znear: camera.near
  552. };
  553. } else {
  554. gltfCamera.perspective = {
  555. aspectRatio: camera.aspect,
  556. yfov: THREE.Math.degToRad( camera.fov ) / camera.aspect,
  557. zfar: camera.far,
  558. znear: camera.near
  559. };
  560. }
  561. if ( camera.name ) {
  562. gltfCamera.name = camera.type;
  563. }
  564. outputJSON.cameras.push( gltfCamera );
  565. return outputJSON.cameras.length - 1;
  566. }
  567. /**
  568. * Creates glTF animation entry from AnimationClip object.
  569. *
  570. * Status:
  571. * - Only properties listed in PATH_PROPERTIES may be animated.
  572. * - Only LINEAR and STEP interpolation currently supported.
  573. *
  574. * @param {THREE.AnimationClip} clip
  575. * @param {THREE.Object3D} root
  576. * @return {number}
  577. */
  578. function processAnimation ( clip, root ) {
  579. if ( ! outputJSON.animations ) {
  580. outputJSON.animations = [];
  581. }
  582. var channels = [];
  583. var samplers = [];
  584. for ( var i = 0; i < clip.tracks.length; ++ i ) {
  585. var track = clip.tracks[ i ];
  586. var trackBinding = THREE.PropertyBinding.parseTrackName( track.name );
  587. var trackNode = THREE.PropertyBinding.findNode( root, trackBinding.nodeName );
  588. var trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];
  589. if ( trackBinding.objectName === 'bones' ) {
  590. if ( trackNode.isSkinnedMesh === true ) {
  591. trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );
  592. } else {
  593. trackNode = undefined;
  594. }
  595. }
  596. if ( ! trackNode || ! trackProperty ) {
  597. console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
  598. return null;
  599. }
  600. var inputItemSize = 1;
  601. var outputItemSize = track.values.length / track.times.length;
  602. if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {
  603. outputItemSize /= trackNode.morphTargetInfluences.length;
  604. }
  605. samplers.push( {
  606. input: processAccessor( new THREE.BufferAttribute( track.times, inputItemSize ) ),
  607. output: processAccessor( new THREE.BufferAttribute( track.values, outputItemSize ) ),
  608. interpolation: track.getInterpolation() === THREE.InterpolateDiscrete ? 'STEP' : 'LINEAR'
  609. } );
  610. channels.push( {
  611. sampler: samplers.length - 1,
  612. target: {
  613. node: nodeMap[ trackNode.uuid ],
  614. path: trackProperty
  615. }
  616. } );
  617. }
  618. outputJSON.animations.push( {
  619. name: clip.name || 'clip_' + outputJSON.animations.length,
  620. samplers: samplers,
  621. channels: channels
  622. } );
  623. return outputJSON.animations.length - 1;
  624. }
  625. function processSkin( object ) {
  626. var node = outputJSON.nodes[ nodeMap[ object.uuid ] ];
  627. var skeleton = object.skeleton;
  628. var rootJoint = object.skeleton.bones[ 0 ];
  629. if ( rootJoint === undefined ) return null;
  630. var joints = [];
  631. var inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );
  632. for ( var i = 0; i < skeleton.bones.length; ++ i ) {
  633. joints.push( nodeMap[ skeleton.bones[ i ].uuid ] );
  634. skeleton.boneInverses[ i ].toArray( inverseBindMatrices, i * 16 );
  635. }
  636. if ( outputJSON.skins === undefined ) {
  637. outputJSON.skins = [];
  638. }
  639. outputJSON.skins.push( {
  640. inverseBindMatrices: processAccessor( new THREE.BufferAttribute( inverseBindMatrices, 16 ) ),
  641. joints: joints,
  642. skeleton: nodeMap[ rootJoint.uuid ]
  643. } );
  644. var skinIndex = node.skin = outputJSON.skins.length - 1;
  645. return skinIndex;
  646. }
  647. /**
  648. * Process Object3D node
  649. * @param {THREE.Object3D} node Object3D to processNode
  650. * @return {Integer} Index of the node in the nodes list
  651. */
  652. function processNode( object ) {
  653. if ( object instanceof THREE.Light ) {
  654. console.warn( 'GLTFExporter: Unsupported node type:', object.constructor.name );
  655. return null;
  656. }
  657. if ( ! outputJSON.nodes ) {
  658. outputJSON.nodes = [];
  659. }
  660. var gltfNode = {};
  661. if ( options.trs ) {
  662. var rotation = object.quaternion.toArray();
  663. var position = object.position.toArray();
  664. var scale = object.scale.toArray();
  665. if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
  666. gltfNode.rotation = rotation;
  667. }
  668. if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
  669. gltfNode.translation = position;
  670. }
  671. if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
  672. gltfNode.scale = scale;
  673. }
  674. } else {
  675. object.updateMatrix();
  676. if ( ! equalArray( object.matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] ) ) {
  677. gltfNode.matrix = object.matrix.elements;
  678. }
  679. }
  680. if ( object.name ) {
  681. gltfNode.name = String( object.name );
  682. }
  683. if ( object.userData && Object.keys( object.userData ).length > 0 ) {
  684. try {
  685. gltfNode.extras = JSON.parse( JSON.stringify( object.userData ) );
  686. } catch ( e ) {
  687. throw new Error( 'THREE.GLTFExporter: userData can\'t be serialized' );
  688. }
  689. }
  690. if ( object instanceof THREE.Mesh ||
  691. object instanceof THREE.Line ||
  692. object instanceof THREE.Points ) {
  693. gltfNode.mesh = processMesh( object );
  694. } else if ( object instanceof THREE.Camera ) {
  695. gltfNode.camera = processCamera( object );
  696. }
  697. if ( object instanceof THREE.SkinnedMesh ) {
  698. skins.push( object );
  699. }
  700. if ( object.children.length > 0 ) {
  701. var children = [];
  702. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  703. var child = object.children[ i ];
  704. if ( child.visible || options.onlyVisible === false ) {
  705. var node = processNode( child );
  706. if ( node !== null ) {
  707. children.push( node );
  708. }
  709. }
  710. }
  711. if ( children.length > 0 ) {
  712. gltfNode.children = children;
  713. }
  714. }
  715. outputJSON.nodes.push( gltfNode );
  716. var nodeIndex = nodeMap[ object.uuid ] = outputJSON.nodes.length - 1;
  717. return nodeIndex;
  718. }
  719. /**
  720. * Process Scene
  721. * @param {THREE.Scene} node Scene to process
  722. */
  723. function processScene( scene ) {
  724. if ( ! outputJSON.scenes ) {
  725. outputJSON.scenes = [];
  726. outputJSON.scene = 0;
  727. }
  728. var gltfScene = {
  729. nodes: []
  730. };
  731. if ( scene.name ) {
  732. gltfScene.name = scene.name;
  733. }
  734. outputJSON.scenes.push( gltfScene );
  735. var nodes = [];
  736. for ( var i = 0, l = scene.children.length; i < l; i ++ ) {
  737. var child = scene.children[ i ];
  738. if ( child.visible || options.onlyVisible === false ) {
  739. var node = processNode( child );
  740. if ( node !== null ) {
  741. nodes.push( node );
  742. }
  743. }
  744. }
  745. if ( nodes.length > 0 ) {
  746. gltfScene.nodes = nodes;
  747. }
  748. }
  749. /**
  750. * Creates a THREE.Scene to hold a list of objects and parse it
  751. * @param {Array} objects List of objects to process
  752. */
  753. function processObjects( objects ) {
  754. var scene = new THREE.Scene();
  755. scene.name = 'AuxScene';
  756. for ( var i = 0; i < objects.length; i ++ ) {
  757. // We push directly to children instead of calling `add` to prevent
  758. // modify the .parent and break its original scene and hierarchy
  759. scene.children.push( objects[ i ] );
  760. }
  761. processScene( scene );
  762. }
  763. function processInput( input ) {
  764. input = input instanceof Array ? input : [ input ];
  765. var objectsWithoutScene = [];
  766. for ( var i = 0; i < input.length; i ++ ) {
  767. if ( input[ i ] instanceof THREE.Scene ) {
  768. processScene( input[ i ] );
  769. } else {
  770. objectsWithoutScene.push( input[ i ] );
  771. }
  772. }
  773. if ( objectsWithoutScene.length > 0 ) {
  774. processObjects( objectsWithoutScene );
  775. }
  776. for ( var i = 0; i < skins.length; ++ i ) {
  777. processSkin( skins[ i ] );
  778. }
  779. for ( var i = 0; i < options.animations.length; ++ i ) {
  780. processAnimation( options.animations[ i ], input[ 0 ] );
  781. }
  782. }
  783. processInput( input );
  784. // Generate buffer
  785. // Create a new blob with all the dataviews from the buffers
  786. var blob = new Blob( dataViews, { type: 'application/octet-stream' } );
  787. // Update the bytlength of the only main buffer and update the uri with the base64 representation of it
  788. if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) {
  789. outputJSON.buffers[ 0 ].byteLength = blob.size;
  790. var reader = new window.FileReader();
  791. if ( options.binary === true ) {
  792. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
  793. var GLB_HEADER_BYTES = 12;
  794. var GLB_HEADER_MAGIC = 0x46546C67;
  795. var GLB_VERSION = 2;
  796. var GLB_CHUNK_PREFIX_BYTES = 8;
  797. var GLB_CHUNK_TYPE_JSON = 0x4E4F534A;
  798. var GLB_CHUNK_TYPE_BIN = 0x004E4942;
  799. reader.readAsArrayBuffer( blob );
  800. reader.onloadend = function () {
  801. // Binary chunk.
  802. var binaryChunk = reader.result;
  803. var binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  804. binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true );
  805. binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true );
  806. // JSON chunk.
  807. delete outputJSON.buffers[ 0 ].uri; // Omitted URI indicates use of binary chunk.
  808. var jsonChunk = stringToArrayBuffer( JSON.stringify( outputJSON ) );
  809. var jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  810. jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true );
  811. jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true );
  812. // GLB header.
  813. var header = new ArrayBuffer( GLB_HEADER_BYTES );
  814. var headerView = new DataView( header );
  815. headerView.setUint32( 0, GLB_HEADER_MAGIC, true );
  816. headerView.setUint32( 4, GLB_VERSION, true );
  817. var totalByteLength = GLB_HEADER_BYTES
  818. + jsonChunkPrefix.byteLength + jsonChunk.byteLength
  819. + binaryChunkPrefix.byteLength + binaryChunk.byteLength;
  820. headerView.setUint32( 8, totalByteLength, true );
  821. var glbBlob = new Blob( [
  822. header,
  823. jsonChunkPrefix,
  824. jsonChunk,
  825. binaryChunkPrefix,
  826. binaryChunk
  827. ], { type: 'application/octet-stream' } );
  828. var glbReader = new window.FileReader();
  829. glbReader.readAsArrayBuffer( glbBlob );
  830. glbReader.onloadend = function () {
  831. onDone( glbReader.result );
  832. };
  833. };
  834. } else {
  835. reader.readAsDataURL( blob );
  836. reader.onloadend = function () {
  837. var base64data = reader.result;
  838. outputJSON.buffers[ 0 ].uri = base64data;
  839. onDone( outputJSON );
  840. };
  841. }
  842. } else {
  843. onDone( outputJSON );
  844. }
  845. }
  846. };