GLTFExporter.js 53 KB

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