GLTFExporter.js 50 KB

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