GLTFExporter.js 53 KB

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