GLTFExporter.js 53 KB

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