GLTFExporter.js 53 KB

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