GLTFExporter.js 72 KB

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