GLTFExporter.js 52 KB

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