GLTFExporter.js 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320
  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. 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 _Math.isPowerOfTwo( image.width ) && _Math.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 = _Math.floorPowerOfTwo( canvas.width );
  519. canvas.height = _Math.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.isMeshBasicMaterial ||
  669. material.isLineBasicMaterial ||
  670. material.isPointsMaterial ) {
  671. } else {
  672. // emissiveFactor
  673. var emissive = material.emissive.clone().multiplyScalar( material.emissiveIntensity ).toArray();
  674. if ( ! equalArray( emissive, [ 0, 0, 0 ] ) ) {
  675. gltfMaterial.emissiveFactor = emissive;
  676. }
  677. // emissiveTexture
  678. if ( material.emissiveMap ) {
  679. var emissiveMapDef = { index: processTexture( material.emissiveMap ) };
  680. applyTextureTransform( emissiveMapDef, material.emissiveMap );
  681. gltfMaterial.emissiveTexture = emissiveMapDef;
  682. }
  683. }
  684. // normalTexture
  685. if ( material.normalMap ) {
  686. var normalMapDef = { index: processTexture( material.normalMap ) };
  687. if ( material.normalScale && material.normalScale.x !== - 1 ) {
  688. if ( material.normalScale.x !== material.normalScale.y ) {
  689. console.warn( 'THREE.GLTFExporter: Normal scale components are different, ignoring Y and exporting X.' );
  690. }
  691. normalMapDef.scale = material.normalScale.x;
  692. }
  693. applyTextureTransform( normalMapDef, material.normalMap );
  694. gltfMaterial.normalTexture = normalMapDef;
  695. }
  696. // occlusionTexture
  697. if ( material.aoMap ) {
  698. var occlusionMapDef = {
  699. index: processTexture( material.aoMap ),
  700. texCoord: 1
  701. };
  702. if ( material.aoMapIntensity !== 1.0 ) {
  703. occlusionMapDef.strength = material.aoMapIntensity;
  704. }
  705. applyTextureTransform( occlusionMapDef, material.aoMap );
  706. gltfMaterial.occlusionTexture = occlusionMapDef;
  707. }
  708. // alphaMode
  709. if ( material.transparent ) {
  710. gltfMaterial.alphaMode = 'BLEND';
  711. } else {
  712. if ( material.alphaTest > 0.0 ) {
  713. gltfMaterial.alphaMode = 'MASK';
  714. gltfMaterial.alphaCutoff = material.alphaTest;
  715. }
  716. }
  717. // doubleSided
  718. if ( material.side === DoubleSide ) {
  719. gltfMaterial.doubleSided = true;
  720. }
  721. if ( material.name !== '' ) {
  722. gltfMaterial.name = material.name;
  723. }
  724. serializeUserData( material, gltfMaterial );
  725. outputJSON.materials.push( gltfMaterial );
  726. var index = outputJSON.materials.length - 1;
  727. cachedData.materials.set( material, index );
  728. return index;
  729. }
  730. /**
  731. * Process mesh
  732. * @param {THREE.Mesh} mesh Mesh to process
  733. * @return {Integer} Index of the processed mesh in the "meshes" array
  734. */
  735. function processMesh( mesh ) {
  736. var cacheKey = mesh.geometry.uuid + ':' + mesh.material.uuid;
  737. if ( cachedData.meshes.has( cacheKey ) ) {
  738. return cachedData.meshes.get( cacheKey );
  739. }
  740. var geometry = mesh.geometry;
  741. var mode;
  742. // Use the correct mode
  743. if ( mesh.isLineSegments ) {
  744. mode = WEBGL_CONSTANTS.LINES;
  745. } else if ( mesh.isLineLoop ) {
  746. mode = WEBGL_CONSTANTS.LINE_LOOP;
  747. } else if ( mesh.isLine ) {
  748. mode = WEBGL_CONSTANTS.LINE_STRIP;
  749. } else if ( mesh.isPoints ) {
  750. mode = WEBGL_CONSTANTS.POINTS;
  751. } else {
  752. if ( ! geometry.isBufferGeometry ) {
  753. console.warn( 'GLTFExporter: Exporting THREE.Geometry will increase file size. Use BufferGeometry instead.' );
  754. var geometryTemp = new BufferGeometry();
  755. geometryTemp.fromGeometry( geometry );
  756. geometry = geometryTemp;
  757. }
  758. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
  759. }
  760. var gltfMesh = {};
  761. var attributes = {};
  762. var primitives = [];
  763. var targets = [];
  764. // Conversion between attributes names in threejs and gltf spec
  765. var nameConversion = {
  766. uv: 'TEXCOORD_0',
  767. uv2: 'TEXCOORD_1',
  768. color: 'COLOR_0',
  769. skinWeight: 'WEIGHTS_0',
  770. skinIndex: 'JOINTS_0'
  771. };
  772. var originalNormal = geometry.getAttribute( 'normal' );
  773. if ( originalNormal !== undefined && ! isNormalizedNormalAttribute( originalNormal ) ) {
  774. console.warn( 'THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.' );
  775. geometry.setAttribute( 'normal', createNormalizedNormalAttribute( originalNormal ) );
  776. }
  777. // @QUESTION Detect if .vertexColors = THREE.VertexColors?
  778. // For every attribute create an accessor
  779. var modifiedAttribute = null;
  780. for ( var attributeName in geometry.attributes ) {
  781. // Ignore morph target attributes, which are exported later.
  782. if ( attributeName.substr( 0, 5 ) === 'morph' ) continue;
  783. var attribute = geometry.attributes[ attributeName ];
  784. attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
  785. // Prefix all geometry attributes except the ones specifically
  786. // listed in the spec; non-spec attributes are considered custom.
  787. var validVertexAttributes =
  788. /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;
  789. if ( ! validVertexAttributes.test( attributeName ) ) {
  790. attributeName = '_' + attributeName;
  791. }
  792. if ( cachedData.attributes.has( getUID( attribute ) ) ) {
  793. attributes[ attributeName ] = cachedData.attributes.get( getUID( attribute ) );
  794. continue;
  795. }
  796. // JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT.
  797. modifiedAttribute = null;
  798. var array = attribute.array;
  799. if ( attributeName === 'JOINTS_0' &&
  800. ! ( array instanceof Uint16Array ) &&
  801. ! ( array instanceof Uint8Array ) ) {
  802. console.warn( 'GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.' );
  803. modifiedAttribute = new BufferAttribute( new Uint16Array( array ), attribute.itemSize, attribute.normalized );
  804. }
  805. var accessor = processAccessor( modifiedAttribute || attribute, geometry );
  806. if ( accessor !== null ) {
  807. attributes[ attributeName ] = accessor;
  808. cachedData.attributes.set( getUID( attribute ), accessor );
  809. }
  810. }
  811. if ( originalNormal !== undefined ) geometry.setAttribute( 'normal', originalNormal );
  812. // Skip if no exportable attributes found
  813. if ( Object.keys( attributes ).length === 0 ) {
  814. return null;
  815. }
  816. // Morph targets
  817. if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) {
  818. var weights = [];
  819. var targetNames = [];
  820. var reverseDictionary = {};
  821. if ( mesh.morphTargetDictionary !== undefined ) {
  822. for ( var key in mesh.morphTargetDictionary ) {
  823. reverseDictionary[ mesh.morphTargetDictionary[ key ] ] = key;
  824. }
  825. }
  826. for ( var i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {
  827. var target = {};
  828. var warned = false;
  829. for ( var attributeName in geometry.morphAttributes ) {
  830. // glTF 2.0 morph supports only POSITION/NORMAL/TANGENT.
  831. // Three.js doesn't support TANGENT yet.
  832. if ( attributeName !== 'position' && attributeName !== 'normal' ) {
  833. if ( ! warned ) {
  834. console.warn( 'GLTFExporter: Only POSITION and NORMAL morph are supported.' );
  835. warned = true;
  836. }
  837. continue;
  838. }
  839. var attribute = geometry.morphAttributes[ attributeName ][ i ];
  840. var gltfAttributeName = attributeName.toUpperCase();
  841. // Three.js morph attribute has absolute values while the one of glTF has relative values.
  842. //
  843. // glTF 2.0 Specification:
  844. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets
  845. var baseAttribute = geometry.attributes[ attributeName ];
  846. if ( cachedData.attributes.has( getUID( attribute ) ) ) {
  847. target[ gltfAttributeName ] = cachedData.attributes.get( getUID( attribute ) );
  848. continue;
  849. }
  850. // Clones attribute not to override
  851. var relativeAttribute = attribute.clone();
  852. if ( ! geometry.morphTargetsRelative ) {
  853. for ( var j = 0, jl = attribute.count; j < jl; j ++ ) {
  854. relativeAttribute.setXYZ(
  855. j,
  856. attribute.getX( j ) - baseAttribute.getX( j ),
  857. attribute.getY( j ) - baseAttribute.getY( j ),
  858. attribute.getZ( j ) - baseAttribute.getZ( j )
  859. );
  860. }
  861. }
  862. target[ gltfAttributeName ] = processAccessor( relativeAttribute, geometry );
  863. cachedData.attributes.set( getUID( baseAttribute ), target[ gltfAttributeName ] );
  864. }
  865. targets.push( target );
  866. weights.push( mesh.morphTargetInfluences[ i ] );
  867. if ( mesh.morphTargetDictionary !== undefined ) targetNames.push( reverseDictionary[ i ] );
  868. }
  869. gltfMesh.weights = weights;
  870. if ( targetNames.length > 0 ) {
  871. gltfMesh.extras = {};
  872. gltfMesh.extras.targetNames = targetNames;
  873. }
  874. }
  875. var forceIndices = options.forceIndices;
  876. var isMultiMaterial = Array.isArray( mesh.material );
  877. if ( isMultiMaterial && geometry.groups.length === 0 ) return null;
  878. if ( ! forceIndices && geometry.index === null && isMultiMaterial ) {
  879. // temporal workaround.
  880. console.warn( 'THREE.GLTFExporter: Creating index for non-indexed multi-material mesh.' );
  881. forceIndices = true;
  882. }
  883. var didForceIndices = false;
  884. if ( geometry.index === null && forceIndices ) {
  885. var indices = [];
  886. for ( var i = 0, il = geometry.attributes.position.count; i < il; i ++ ) {
  887. indices[ i ] = i;
  888. }
  889. geometry.setIndex( indices );
  890. didForceIndices = true;
  891. }
  892. var materials = isMultiMaterial ? mesh.material : [ mesh.material ];
  893. var groups = isMultiMaterial ? geometry.groups : [ { materialIndex: 0, start: undefined, count: undefined } ];
  894. for ( var i = 0, il = groups.length; i < il; i ++ ) {
  895. var primitive = {
  896. mode: mode,
  897. attributes: attributes,
  898. };
  899. serializeUserData( geometry, primitive );
  900. if ( targets.length > 0 ) primitive.targets = targets;
  901. if ( geometry.index !== null ) {
  902. var cacheKey = getUID( geometry.index );
  903. if ( groups[ i ].start !== undefined || groups[ i ].count !== undefined ) {
  904. cacheKey += ':' + groups[ i ].start + ':' + groups[ i ].count;
  905. }
  906. if ( cachedData.attributes.has( cacheKey ) ) {
  907. primitive.indices = cachedData.attributes.get( cacheKey );
  908. } else {
  909. primitive.indices = processAccessor( geometry.index, geometry, groups[ i ].start, groups[ i ].count );
  910. cachedData.attributes.set( cacheKey, primitive.indices );
  911. }
  912. if ( primitive.indices === null ) delete primitive.indices;
  913. }
  914. var material = processMaterial( materials[ groups[ i ].materialIndex ] );
  915. if ( material !== null ) {
  916. primitive.material = material;
  917. }
  918. primitives.push( primitive );
  919. }
  920. if ( didForceIndices ) {
  921. geometry.setIndex( null );
  922. }
  923. gltfMesh.primitives = primitives;
  924. if ( ! outputJSON.meshes ) {
  925. outputJSON.meshes = [];
  926. }
  927. outputJSON.meshes.push( gltfMesh );
  928. var index = outputJSON.meshes.length - 1;
  929. cachedData.meshes.set( cacheKey, index );
  930. return index;
  931. }
  932. /**
  933. * Process camera
  934. * @param {THREE.Camera} camera Camera to process
  935. * @return {Integer} Index of the processed mesh in the "camera" array
  936. */
  937. function processCamera( camera ) {
  938. if ( ! outputJSON.cameras ) {
  939. outputJSON.cameras = [];
  940. }
  941. var isOrtho = camera.isOrthographicCamera;
  942. var gltfCamera = {
  943. type: isOrtho ? 'orthographic' : 'perspective'
  944. };
  945. if ( isOrtho ) {
  946. gltfCamera.orthographic = {
  947. xmag: camera.right * 2,
  948. ymag: camera.top * 2,
  949. zfar: camera.far <= 0 ? 0.001 : camera.far,
  950. znear: camera.near < 0 ? 0 : camera.near
  951. };
  952. } else {
  953. gltfCamera.perspective = {
  954. aspectRatio: camera.aspect,
  955. yfov: _Math.degToRad( camera.fov ),
  956. zfar: camera.far <= 0 ? 0.001 : camera.far,
  957. znear: camera.near < 0 ? 0 : camera.near
  958. };
  959. }
  960. if ( camera.name !== '' ) {
  961. gltfCamera.name = camera.type;
  962. }
  963. outputJSON.cameras.push( gltfCamera );
  964. return outputJSON.cameras.length - 1;
  965. }
  966. /**
  967. * Creates glTF animation entry from AnimationClip object.
  968. *
  969. * Status:
  970. * - Only properties listed in PATH_PROPERTIES may be animated.
  971. *
  972. * @param {THREE.AnimationClip} clip
  973. * @param {THREE.Object3D} root
  974. * @return {number}
  975. */
  976. function processAnimation( clip, root ) {
  977. if ( ! outputJSON.animations ) {
  978. outputJSON.animations = [];
  979. }
  980. clip = GLTFExporter.Utils.mergeMorphTargetTracks( clip.clone(), root );
  981. var tracks = clip.tracks;
  982. var channels = [];
  983. var samplers = [];
  984. for ( var i = 0; i < tracks.length; ++ i ) {
  985. var track = tracks[ i ];
  986. var trackBinding = PropertyBinding.parseTrackName( track.name );
  987. var trackNode = PropertyBinding.findNode( root, trackBinding.nodeName );
  988. var trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];
  989. if ( trackBinding.objectName === 'bones' ) {
  990. if ( trackNode.isSkinnedMesh === true ) {
  991. trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );
  992. } else {
  993. trackNode = undefined;
  994. }
  995. }
  996. if ( ! trackNode || ! trackProperty ) {
  997. console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
  998. return null;
  999. }
  1000. var inputItemSize = 1;
  1001. var outputItemSize = track.values.length / track.times.length;
  1002. if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {
  1003. outputItemSize /= trackNode.morphTargetInfluences.length;
  1004. }
  1005. var interpolation;
  1006. // @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE
  1007. // Detecting glTF cubic spline interpolant by checking factory method's special property
  1008. // GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return
  1009. // valid value from .getInterpolation().
  1010. if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) {
  1011. interpolation = 'CUBICSPLINE';
  1012. // itemSize of CUBICSPLINE keyframe is 9
  1013. // (VEC3 * 3: inTangent, splineVertex, and outTangent)
  1014. // but needs to be stored as VEC3 so dividing by 3 here.
  1015. outputItemSize /= 3;
  1016. } else if ( track.getInterpolation() === InterpolateDiscrete ) {
  1017. interpolation = 'STEP';
  1018. } else {
  1019. interpolation = 'LINEAR';
  1020. }
  1021. samplers.push( {
  1022. input: processAccessor( new BufferAttribute( track.times, inputItemSize ) ),
  1023. output: processAccessor( new BufferAttribute( track.values, outputItemSize ) ),
  1024. interpolation: interpolation
  1025. } );
  1026. channels.push( {
  1027. sampler: samplers.length - 1,
  1028. target: {
  1029. node: nodeMap.get( trackNode ),
  1030. path: trackProperty
  1031. }
  1032. } );
  1033. }
  1034. outputJSON.animations.push( {
  1035. name: clip.name || 'clip_' + outputJSON.animations.length,
  1036. samplers: samplers,
  1037. channels: channels
  1038. } );
  1039. return outputJSON.animations.length - 1;
  1040. }
  1041. function processSkin( object ) {
  1042. var node = outputJSON.nodes[ nodeMap.get( object ) ];
  1043. var skeleton = object.skeleton;
  1044. var rootJoint = object.skeleton.bones[ 0 ];
  1045. if ( rootJoint === undefined ) return null;
  1046. var joints = [];
  1047. var inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );
  1048. for ( var i = 0; i < skeleton.bones.length; ++ i ) {
  1049. joints.push( nodeMap.get( skeleton.bones[ i ] ) );
  1050. skeleton.boneInverses[ i ].toArray( inverseBindMatrices, i * 16 );
  1051. }
  1052. if ( outputJSON.skins === undefined ) {
  1053. outputJSON.skins = [];
  1054. }
  1055. outputJSON.skins.push( {
  1056. inverseBindMatrices: processAccessor( new BufferAttribute( inverseBindMatrices, 16 ) ),
  1057. joints: joints,
  1058. skeleton: nodeMap.get( rootJoint )
  1059. } );
  1060. var skinIndex = node.skin = outputJSON.skins.length - 1;
  1061. return skinIndex;
  1062. }
  1063. function processLight( light ) {
  1064. var lightDef = {};
  1065. if ( light.name ) lightDef.name = light.name;
  1066. lightDef.color = light.color.toArray();
  1067. lightDef.intensity = light.intensity;
  1068. if ( light.isDirectionalLight ) {
  1069. lightDef.type = 'directional';
  1070. } else if ( light.isPointLight ) {
  1071. lightDef.type = 'point';
  1072. if ( light.distance > 0 ) lightDef.range = light.distance;
  1073. } else if ( light.isSpotLight ) {
  1074. lightDef.type = 'spot';
  1075. if ( light.distance > 0 ) lightDef.range = light.distance;
  1076. lightDef.spot = {};
  1077. lightDef.spot.innerConeAngle = ( light.penumbra - 1.0 ) * light.angle * - 1.0;
  1078. lightDef.spot.outerConeAngle = light.angle;
  1079. }
  1080. if ( light.decay !== undefined && light.decay !== 2 ) {
  1081. console.warn( 'THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, '
  1082. + 'and expects light.decay=2.' );
  1083. }
  1084. if ( light.target
  1085. && ( light.target.parent !== light
  1086. || light.target.position.x !== 0
  1087. || light.target.position.y !== 0
  1088. || light.target.position.z !== - 1 ) ) {
  1089. console.warn( 'THREE.GLTFExporter: Light direction may be lost. For best results, '
  1090. + 'make light.target a child of the light with position 0,0,-1.' );
  1091. }
  1092. var lights = outputJSON.extensions[ 'KHR_lights_punctual' ].lights;
  1093. lights.push( lightDef );
  1094. return lights.length - 1;
  1095. }
  1096. /**
  1097. * Process Object3D node
  1098. * @param {THREE.Object3D} node Object3D to processNode
  1099. * @return {Integer} Index of the node in the nodes list
  1100. */
  1101. function processNode( object ) {
  1102. if ( ! outputJSON.nodes ) {
  1103. outputJSON.nodes = [];
  1104. }
  1105. var gltfNode = {};
  1106. if ( options.trs ) {
  1107. var rotation = object.quaternion.toArray();
  1108. var position = object.position.toArray();
  1109. var scale = object.scale.toArray();
  1110. if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
  1111. gltfNode.rotation = rotation;
  1112. }
  1113. if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
  1114. gltfNode.translation = position;
  1115. }
  1116. if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
  1117. gltfNode.scale = scale;
  1118. }
  1119. } else {
  1120. if ( object.matrixAutoUpdate ) {
  1121. object.updateMatrix();
  1122. }
  1123. if ( ! equalArray( object.matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] ) ) {
  1124. gltfNode.matrix = object.matrix.elements;
  1125. }
  1126. }
  1127. // We don't export empty strings name because it represents no-name in Three.js.
  1128. if ( object.name !== '' ) {
  1129. gltfNode.name = String( object.name );
  1130. }
  1131. serializeUserData( object, gltfNode );
  1132. if ( object.isMesh || object.isLine || object.isPoints ) {
  1133. var mesh = processMesh( object );
  1134. if ( mesh !== null ) {
  1135. gltfNode.mesh = mesh;
  1136. }
  1137. } else if ( object.isCamera ) {
  1138. gltfNode.camera = processCamera( object );
  1139. } else if ( object.isDirectionalLight || object.isPointLight || object.isSpotLight ) {
  1140. if ( ! extensionsUsed[ 'KHR_lights_punctual' ] ) {
  1141. outputJSON.extensions = outputJSON.extensions || {};
  1142. outputJSON.extensions[ 'KHR_lights_punctual' ] = { lights: [] };
  1143. extensionsUsed[ 'KHR_lights_punctual' ] = true;
  1144. }
  1145. gltfNode.extensions = gltfNode.extensions || {};
  1146. gltfNode.extensions[ 'KHR_lights_punctual' ] = { light: processLight( object ) };
  1147. } else if ( object.isLight ) {
  1148. console.warn( 'THREE.GLTFExporter: Only directional, point, and spot lights are supported.', object );
  1149. return null;
  1150. }
  1151. if ( object.isSkinnedMesh ) {
  1152. skins.push( object );
  1153. }
  1154. if ( object.children.length > 0 ) {
  1155. var children = [];
  1156. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  1157. var child = object.children[ i ];
  1158. if ( child.visible || options.onlyVisible === false ) {
  1159. var node = processNode( child );
  1160. if ( node !== null ) {
  1161. children.push( node );
  1162. }
  1163. }
  1164. }
  1165. if ( children.length > 0 ) {
  1166. gltfNode.children = children;
  1167. }
  1168. }
  1169. outputJSON.nodes.push( gltfNode );
  1170. var nodeIndex = outputJSON.nodes.length - 1;
  1171. nodeMap.set( object, nodeIndex );
  1172. return nodeIndex;
  1173. }
  1174. /**
  1175. * Process Scene
  1176. * @param {Scene} node Scene to process
  1177. */
  1178. function processScene( scene ) {
  1179. if ( ! outputJSON.scenes ) {
  1180. outputJSON.scenes = [];
  1181. outputJSON.scene = 0;
  1182. }
  1183. var gltfScene = {
  1184. nodes: []
  1185. };
  1186. if ( scene.name !== '' ) {
  1187. gltfScene.name = scene.name;
  1188. }
  1189. if ( scene.userData && Object.keys( scene.userData ).length > 0 ) {
  1190. gltfScene.extras = serializeUserData( scene );
  1191. }
  1192. outputJSON.scenes.push( gltfScene );
  1193. var nodes = [];
  1194. for ( var i = 0, l = scene.children.length; i < l; i ++ ) {
  1195. var child = scene.children[ i ];
  1196. if ( child.visible || options.onlyVisible === false ) {
  1197. var node = processNode( child );
  1198. if ( node !== null ) {
  1199. nodes.push( node );
  1200. }
  1201. }
  1202. }
  1203. if ( nodes.length > 0 ) {
  1204. gltfScene.nodes = nodes;
  1205. }
  1206. serializeUserData( scene, gltfScene );
  1207. }
  1208. /**
  1209. * Creates a Scene to hold a list of objects and parse it
  1210. * @param {Array} objects List of objects to process
  1211. */
  1212. function processObjects( objects ) {
  1213. var scene = new Scene();
  1214. scene.name = 'AuxScene';
  1215. for ( var i = 0; i < objects.length; i ++ ) {
  1216. // We push directly to children instead of calling `add` to prevent
  1217. // modify the .parent and break its original scene and hierarchy
  1218. scene.children.push( objects[ i ] );
  1219. }
  1220. processScene( scene );
  1221. }
  1222. function processInput( input ) {
  1223. input = input instanceof Array ? input : [ input ];
  1224. var objectsWithoutScene = [];
  1225. for ( var i = 0; i < input.length; i ++ ) {
  1226. if ( input[ i ] instanceof Scene ) {
  1227. processScene( input[ i ] );
  1228. } else {
  1229. objectsWithoutScene.push( input[ i ] );
  1230. }
  1231. }
  1232. if ( objectsWithoutScene.length > 0 ) {
  1233. processObjects( objectsWithoutScene );
  1234. }
  1235. for ( var i = 0; i < skins.length; ++ i ) {
  1236. processSkin( skins[ i ] );
  1237. }
  1238. for ( var i = 0; i < options.animations.length; ++ i ) {
  1239. processAnimation( options.animations[ i ], input[ 0 ] );
  1240. }
  1241. }
  1242. processInput( input );
  1243. Promise.all( pending ).then( function () {
  1244. // Merge buffers.
  1245. var blob = new Blob( buffers, { type: 'application/octet-stream' } );
  1246. // Declare extensions.
  1247. var extensionsUsedList = Object.keys( extensionsUsed );
  1248. if ( extensionsUsedList.length > 0 ) outputJSON.extensionsUsed = extensionsUsedList;
  1249. if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) {
  1250. // Update bytelength of the single buffer.
  1251. outputJSON.buffers[ 0 ].byteLength = blob.size;
  1252. var reader = new window.FileReader();
  1253. if ( options.binary === true ) {
  1254. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
  1255. var GLB_HEADER_BYTES = 12;
  1256. var GLB_HEADER_MAGIC = 0x46546C67;
  1257. var GLB_VERSION = 2;
  1258. var GLB_CHUNK_PREFIX_BYTES = 8;
  1259. var GLB_CHUNK_TYPE_JSON = 0x4E4F534A;
  1260. var GLB_CHUNK_TYPE_BIN = 0x004E4942;
  1261. reader.readAsArrayBuffer( blob );
  1262. reader.onloadend = function () {
  1263. // Binary chunk.
  1264. var binaryChunk = getPaddedArrayBuffer( reader.result );
  1265. var binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  1266. binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true );
  1267. binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true );
  1268. // JSON chunk.
  1269. var jsonChunk = getPaddedArrayBuffer( stringToArrayBuffer( JSON.stringify( outputJSON ) ), 0x20 );
  1270. var jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  1271. jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true );
  1272. jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true );
  1273. // GLB header.
  1274. var header = new ArrayBuffer( GLB_HEADER_BYTES );
  1275. var headerView = new DataView( header );
  1276. headerView.setUint32( 0, GLB_HEADER_MAGIC, true );
  1277. headerView.setUint32( 4, GLB_VERSION, true );
  1278. var totalByteLength = GLB_HEADER_BYTES
  1279. + jsonChunkPrefix.byteLength + jsonChunk.byteLength
  1280. + binaryChunkPrefix.byteLength + binaryChunk.byteLength;
  1281. headerView.setUint32( 8, totalByteLength, true );
  1282. var glbBlob = new Blob( [
  1283. header,
  1284. jsonChunkPrefix,
  1285. jsonChunk,
  1286. binaryChunkPrefix,
  1287. binaryChunk
  1288. ], { type: 'application/octet-stream' } );
  1289. var glbReader = new window.FileReader();
  1290. glbReader.readAsArrayBuffer( glbBlob );
  1291. glbReader.onloadend = function () {
  1292. onDone( glbReader.result );
  1293. };
  1294. };
  1295. } else {
  1296. reader.readAsDataURL( blob );
  1297. reader.onloadend = function () {
  1298. var base64data = reader.result;
  1299. outputJSON.buffers[ 0 ].uri = base64data;
  1300. onDone( outputJSON );
  1301. };
  1302. }
  1303. } else {
  1304. onDone( outputJSON );
  1305. }
  1306. } );
  1307. }
  1308. };
  1309. GLTFExporter.Utils = {
  1310. insertKeyframe: function ( track, time ) {
  1311. var tolerance = 0.001; // 1ms
  1312. var valueSize = track.getValueSize();
  1313. var times = new track.TimeBufferType( track.times.length + 1 );
  1314. var values = new track.ValueBufferType( track.values.length + valueSize );
  1315. var interpolant = track.createInterpolant( new track.ValueBufferType( valueSize ) );
  1316. var index;
  1317. if ( track.times.length === 0 ) {
  1318. times[ 0 ] = time;
  1319. for ( var i = 0; i < valueSize; i ++ ) {
  1320. values[ i ] = 0;
  1321. }
  1322. index = 0;
  1323. } else if ( time < track.times[ 0 ] ) {
  1324. if ( Math.abs( track.times[ 0 ] - time ) < tolerance ) return 0;
  1325. times[ 0 ] = time;
  1326. times.set( track.times, 1 );
  1327. values.set( interpolant.evaluate( time ), 0 );
  1328. values.set( track.values, valueSize );
  1329. index = 0;
  1330. } else if ( time > track.times[ track.times.length - 1 ] ) {
  1331. if ( Math.abs( track.times[ track.times.length - 1 ] - time ) < tolerance ) {
  1332. return track.times.length - 1;
  1333. }
  1334. times[ times.length - 1 ] = time;
  1335. times.set( track.times, 0 );
  1336. values.set( track.values, 0 );
  1337. values.set( interpolant.evaluate( time ), track.values.length );
  1338. index = times.length - 1;
  1339. } else {
  1340. for ( var i = 0; i < track.times.length; i ++ ) {
  1341. if ( Math.abs( track.times[ i ] - time ) < tolerance ) return i;
  1342. if ( track.times[ i ] < time && track.times[ i + 1 ] > time ) {
  1343. times.set( track.times.slice( 0, i + 1 ), 0 );
  1344. times[ i + 1 ] = time;
  1345. times.set( track.times.slice( i + 1 ), i + 2 );
  1346. values.set( track.values.slice( 0, ( i + 1 ) * valueSize ), 0 );
  1347. values.set( interpolant.evaluate( time ), ( i + 1 ) * valueSize );
  1348. values.set( track.values.slice( ( i + 1 ) * valueSize ), ( i + 2 ) * valueSize );
  1349. index = i + 1;
  1350. break;
  1351. }
  1352. }
  1353. }
  1354. track.times = times;
  1355. track.values = values;
  1356. return index;
  1357. },
  1358. mergeMorphTargetTracks: function ( clip, root ) {
  1359. var tracks = [];
  1360. var mergedTracks = {};
  1361. var sourceTracks = clip.tracks;
  1362. for ( var i = 0; i < sourceTracks.length; ++ i ) {
  1363. var sourceTrack = sourceTracks[ i ];
  1364. var sourceTrackBinding = PropertyBinding.parseTrackName( sourceTrack.name );
  1365. var sourceTrackNode = PropertyBinding.findNode( root, sourceTrackBinding.nodeName );
  1366. if ( sourceTrackBinding.propertyName !== 'morphTargetInfluences' || sourceTrackBinding.propertyIndex === undefined ) {
  1367. // Tracks that don't affect morph targets, or that affect all morph targets together, can be left as-is.
  1368. tracks.push( sourceTrack );
  1369. continue;
  1370. }
  1371. if ( sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete
  1372. && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear ) {
  1373. if ( sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  1374. // This should never happen, because glTF morph target animations
  1375. // affect all targets already.
  1376. throw new Error( 'THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.' );
  1377. }
  1378. console.warn( 'THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead.' );
  1379. sourceTrack = sourceTrack.clone();
  1380. sourceTrack.setInterpolation( InterpolateLinear );
  1381. }
  1382. var targetCount = sourceTrackNode.morphTargetInfluences.length;
  1383. var targetIndex = sourceTrackNode.morphTargetDictionary[ sourceTrackBinding.propertyIndex ];
  1384. if ( targetIndex === undefined ) {
  1385. throw new Error( 'THREE.GLTFExporter: Morph target name not found: ' + sourceTrackBinding.propertyIndex );
  1386. }
  1387. var mergedTrack;
  1388. // If this is the first time we've seen this object, create a new
  1389. // track to store merged keyframe data for each morph target.
  1390. if ( mergedTracks[ sourceTrackNode.uuid ] === undefined ) {
  1391. mergedTrack = sourceTrack.clone();
  1392. var values = new mergedTrack.ValueBufferType( targetCount * mergedTrack.times.length );
  1393. for ( var j = 0; j < mergedTrack.times.length; j ++ ) {
  1394. values[ j * targetCount + targetIndex ] = mergedTrack.values[ j ];
  1395. }
  1396. mergedTrack.name = '.morphTargetInfluences';
  1397. mergedTrack.values = values;
  1398. mergedTracks[ sourceTrackNode.uuid ] = mergedTrack;
  1399. tracks.push( mergedTrack );
  1400. continue;
  1401. }
  1402. var sourceInterpolant = sourceTrack.createInterpolant( new sourceTrack.ValueBufferType( 1 ) );
  1403. mergedTrack = mergedTracks[ sourceTrackNode.uuid ];
  1404. // For every existing keyframe of the merged track, write a (possibly
  1405. // interpolated) value from the source track.
  1406. for ( var j = 0; j < mergedTrack.times.length; j ++ ) {
  1407. mergedTrack.values[ j * targetCount + targetIndex ] = sourceInterpolant.evaluate( mergedTrack.times[ j ] );
  1408. }
  1409. // For every existing keyframe of the source track, write a (possibly
  1410. // new) keyframe to the merged track. Values from the previous loop may
  1411. // be written again, but keyframes are de-duplicated.
  1412. for ( var j = 0; j < sourceTrack.times.length; j ++ ) {
  1413. var keyframeIndex = this.insertKeyframe( mergedTrack, sourceTrack.times[ j ] );
  1414. mergedTrack.values[ keyframeIndex * targetCount + targetIndex ] = sourceTrack.values[ j ];
  1415. }
  1416. }
  1417. clip.tracks = tracks;
  1418. return clip;
  1419. }
  1420. };
  1421. export { GLTFExporter };