GLTFExporter.js 52 KB

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