GLTFExporter.js 53 KB

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