GLTFExporter.js 52 KB

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