GLTFExporter.js 52 KB

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