GLTFExporter.js 53 KB

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