ColladaExporter.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. import {
  2. Color,
  3. DoubleSide,
  4. Matrix4,
  5. MeshBasicMaterial
  6. } from 'three';
  7. /**
  8. * https://github.com/gkjohnson/collada-exporter-js
  9. *
  10. * Usage:
  11. * const exporter = new ColladaExporter();
  12. *
  13. * const data = exporter.parse(mesh);
  14. *
  15. * Format Definition:
  16. * https://www.khronos.org/collada/
  17. */
  18. class ColladaExporter {
  19. parse( object, onDone, options = {} ) {
  20. options = Object.assign( {
  21. version: '1.4.1',
  22. author: null,
  23. textureDirectory: '',
  24. upAxis: 'Y_UP',
  25. unitName: null,
  26. unitMeter: null,
  27. }, options );
  28. if ( options.upAxis.match( /^[XYZ]_UP$/ ) === null ) {
  29. console.error( 'ColladaExporter: Invalid upAxis: valid values are X_UP, Y_UP or Z_UP.' );
  30. return null;
  31. }
  32. if ( options.unitName !== null && options.unitMeter === null ) {
  33. console.error( 'ColladaExporter: unitMeter needs to be specified if unitName is specified.' );
  34. return null;
  35. }
  36. if ( options.unitMeter !== null && options.unitName === null ) {
  37. console.error( 'ColladaExporter: unitName needs to be specified if unitMeter is specified.' );
  38. return null;
  39. }
  40. if ( options.textureDirectory !== '' ) {
  41. options.textureDirectory = `${ options.textureDirectory }/`
  42. .replace( /\\/g, '/' )
  43. .replace( /\/+/g, '/' );
  44. }
  45. const version = options.version;
  46. if ( version !== '1.4.1' && version !== '1.5.0' ) {
  47. console.warn( `ColladaExporter : Version ${ version } not supported for export. Only 1.4.1 and 1.5.0.` );
  48. return null;
  49. }
  50. // Convert the urdf xml into a well-formatted, indented format
  51. function format( urdf ) {
  52. const IS_END_TAG = /^<\//;
  53. const IS_SELF_CLOSING = /(\?>$)|(\/>$)/;
  54. const HAS_TEXT = /<[^>]+>[^<]*<\/[^<]+>/;
  55. const pad = ( ch, num ) => ( num > 0 ? ch + pad( ch, num - 1 ) : '' );
  56. let tagnum = 0;
  57. return urdf
  58. .match( /(<[^>]+>[^<]+<\/[^<]+>)|(<[^>]+>)/g )
  59. .map( tag => {
  60. if ( ! HAS_TEXT.test( tag ) && ! IS_SELF_CLOSING.test( tag ) && IS_END_TAG.test( tag ) ) {
  61. tagnum --;
  62. }
  63. const res = `${ pad( ' ', tagnum ) }${ tag }`;
  64. if ( ! HAS_TEXT.test( tag ) && ! IS_SELF_CLOSING.test( tag ) && ! IS_END_TAG.test( tag ) ) {
  65. tagnum ++;
  66. }
  67. return res;
  68. } )
  69. .join( '\n' );
  70. }
  71. // Convert an image into a png format for saving
  72. function base64ToBuffer( str ) {
  73. const b = atob( str );
  74. const buf = new Uint8Array( b.length );
  75. for ( let i = 0, l = buf.length; i < l; i ++ ) {
  76. buf[ i ] = b.charCodeAt( i );
  77. }
  78. return buf;
  79. }
  80. let canvas, ctx;
  81. function imageToData( image, ext ) {
  82. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  83. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  84. ( typeof OffscreenCanvas !== 'undefined' && image instanceof OffscreenCanvas ) ||
  85. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  86. canvas = canvas || document.createElement( 'canvas' );
  87. ctx = ctx || canvas.getContext( '2d' );
  88. canvas.width = image.width;
  89. canvas.height = image.height;
  90. ctx.drawImage( image, 0, 0 );
  91. // Get the base64 encoded data
  92. const base64data = canvas
  93. .toDataURL( `image/${ ext }`, 1 )
  94. .replace( /^data:image\/(png|jpg);base64,/, '' );
  95. // Convert to a uint8 array
  96. return base64ToBuffer( base64data );
  97. } else {
  98. throw new Error( 'THREE.ColladaExporter: No valid image data found. Unable to process texture.' );
  99. }
  100. }
  101. // gets the attribute array. Generate a new array if the attribute is interleaved
  102. const getFuncs = [ 'getX', 'getY', 'getZ', 'getW' ];
  103. const tempColor = new Color();
  104. function attrBufferToArray( attr, isColor = false ) {
  105. if ( isColor ) {
  106. // convert the colors to srgb before export
  107. // colors are always written as floats
  108. const arr = new Float32Array( attr.count * 3 );
  109. for ( let i = 0, l = attr.count; i < l; i ++ ) {
  110. tempColor
  111. .fromBufferAttribute( attr, i )
  112. .convertLinearToSRGB();
  113. arr[ 3 * i + 0 ] = tempColor.r;
  114. arr[ 3 * i + 1 ] = tempColor.g;
  115. arr[ 3 * i + 2 ] = tempColor.b;
  116. }
  117. return arr;
  118. } else if ( attr.isInterleavedBufferAttribute ) {
  119. // use the typed array constructor to save on memory
  120. const arr = new attr.array.constructor( attr.count * attr.itemSize );
  121. const size = attr.itemSize;
  122. for ( let i = 0, l = attr.count; i < l; i ++ ) {
  123. for ( let j = 0; j < size; j ++ ) {
  124. arr[ i * size + j ] = attr[ getFuncs[ j ] ]( i );
  125. }
  126. }
  127. return arr;
  128. } else {
  129. return attr.array;
  130. }
  131. }
  132. // Returns an array of the same type starting at the `st` index,
  133. // and `ct` length
  134. function subArray( arr, st, ct ) {
  135. if ( Array.isArray( arr ) ) return arr.slice( st, st + ct );
  136. else return new arr.constructor( arr.buffer, st * arr.BYTES_PER_ELEMENT, ct );
  137. }
  138. // Returns the string for a geometry's attribute
  139. function getAttribute( attr, name, params, type, isColor = false ) {
  140. const array = attrBufferToArray( attr, isColor );
  141. const res =
  142. `<source id="${ name }">` +
  143. `<float_array id="${ name }-array" count="${ array.length }">` +
  144. array.join( ' ' ) +
  145. '</float_array>' +
  146. '<technique_common>' +
  147. `<accessor source="#${ name }-array" count="${ Math.floor( array.length / attr.itemSize ) }" stride="${ attr.itemSize }">` +
  148. params.map( n => `<param name="${ n }" type="${ type }" />` ).join( '' ) +
  149. '</accessor>' +
  150. '</technique_common>' +
  151. '</source>';
  152. return res;
  153. }
  154. // Returns the string for a node's transform information
  155. let transMat;
  156. function getTransform( o ) {
  157. // ensure the object's matrix is up to date
  158. // before saving the transform
  159. o.updateMatrix();
  160. transMat = transMat || new Matrix4();
  161. transMat.copy( o.matrix );
  162. transMat.transpose();
  163. return `<matrix>${ transMat.toArray().join( ' ' ) }</matrix>`;
  164. }
  165. // Process the given piece of geometry into the geometry library
  166. // Returns the mesh id
  167. function processGeometry( bufferGeometry ) {
  168. let info = geometryInfo.get( bufferGeometry );
  169. if ( ! info ) {
  170. const meshid = `Mesh${ libraryGeometries.length + 1 }`;
  171. const indexCount =
  172. bufferGeometry.index ?
  173. bufferGeometry.index.count * bufferGeometry.index.itemSize :
  174. bufferGeometry.attributes.position.count;
  175. const groups =
  176. bufferGeometry.groups != null && bufferGeometry.groups.length !== 0 ?
  177. bufferGeometry.groups :
  178. [ { start: 0, count: indexCount, materialIndex: 0 } ];
  179. const gname = bufferGeometry.name ? ` name="${ bufferGeometry.name }"` : '';
  180. let gnode = `<geometry id="${ meshid }"${ gname }><mesh>`;
  181. // define the geometry node and the vertices for the geometry
  182. const posName = `${ meshid }-position`;
  183. const vertName = `${ meshid }-vertices`;
  184. gnode += getAttribute( bufferGeometry.attributes.position, posName, [ 'X', 'Y', 'Z' ], 'float' );
  185. gnode += `<vertices id="${ vertName }"><input semantic="POSITION" source="#${ posName }" /></vertices>`;
  186. // NOTE: We're not optimizing the attribute arrays here, so they're all the same length and
  187. // can therefore share the same triangle indices. However, MeshLab seems to have trouble opening
  188. // models with attributes that share an offset.
  189. // MeshLab Bug#424: https://sourceforge.net/p/meshlab/bugs/424/
  190. // serialize normals
  191. let triangleInputs = `<input semantic="VERTEX" source="#${ vertName }" offset="0" />`;
  192. if ( 'normal' in bufferGeometry.attributes ) {
  193. const normName = `${ meshid }-normal`;
  194. gnode += getAttribute( bufferGeometry.attributes.normal, normName, [ 'X', 'Y', 'Z' ], 'float' );
  195. triangleInputs += `<input semantic="NORMAL" source="#${ normName }" offset="0" />`;
  196. }
  197. // serialize uvs
  198. if ( 'uv' in bufferGeometry.attributes ) {
  199. const uvName = `${ meshid }-texcoord`;
  200. gnode += getAttribute( bufferGeometry.attributes.uv, uvName, [ 'S', 'T' ], 'float' );
  201. triangleInputs += `<input semantic="TEXCOORD" source="#${ uvName }" offset="0" set="0" />`;
  202. }
  203. // serialize lightmap uvs
  204. if ( 'uv1' in bufferGeometry.attributes ) {
  205. const uvName = `${ meshid }-texcoord2`;
  206. gnode += getAttribute( bufferGeometry.attributes.uv1, uvName, [ 'S', 'T' ], 'float' );
  207. triangleInputs += `<input semantic="TEXCOORD" source="#${ uvName }" offset="0" set="1" />`;
  208. }
  209. // serialize colors
  210. if ( 'color' in bufferGeometry.attributes ) {
  211. // colors are always written as floats
  212. const colName = `${ meshid }-color`;
  213. gnode += getAttribute( bufferGeometry.attributes.color, colName, [ 'R', 'G', 'B' ], 'float', true );
  214. triangleInputs += `<input semantic="COLOR" source="#${ colName }" offset="0" />`;
  215. }
  216. let indexArray = null;
  217. if ( bufferGeometry.index ) {
  218. indexArray = attrBufferToArray( bufferGeometry.index );
  219. } else {
  220. indexArray = new Array( indexCount );
  221. for ( let i = 0, l = indexArray.length; i < l; i ++ ) indexArray[ i ] = i;
  222. }
  223. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  224. const group = groups[ i ];
  225. const subarr = subArray( indexArray, group.start, group.count );
  226. const polycount = subarr.length / 3;
  227. gnode += `<triangles material="MESH_MATERIAL_${ group.materialIndex }" count="${ polycount }">`;
  228. gnode += triangleInputs;
  229. gnode += `<p>${ subarr.join( ' ' ) }</p>`;
  230. gnode += '</triangles>';
  231. }
  232. gnode += '</mesh></geometry>';
  233. libraryGeometries.push( gnode );
  234. info = { meshid: meshid, bufferGeometry: bufferGeometry };
  235. geometryInfo.set( bufferGeometry, info );
  236. }
  237. return info;
  238. }
  239. // Process the given texture into the image library
  240. // Returns the image library
  241. function processTexture( tex ) {
  242. let texid = imageMap.get( tex );
  243. if ( texid === undefined ) {
  244. texid = `image-${ libraryImages.length + 1 }`;
  245. const ext = 'png';
  246. const name = tex.name || texid;
  247. let imageNode = `<image id="${ texid }" name="${ name }">`;
  248. if ( version === '1.5.0' ) {
  249. imageNode += `<init_from><ref>${ options.textureDirectory }${ name }.${ ext }</ref></init_from>`;
  250. } else {
  251. // version image node 1.4.1
  252. imageNode += `<init_from>${ options.textureDirectory }${ name }.${ ext }</init_from>`;
  253. }
  254. imageNode += '</image>';
  255. libraryImages.push( imageNode );
  256. imageMap.set( tex, texid );
  257. textures.push( {
  258. directory: options.textureDirectory,
  259. name,
  260. ext,
  261. data: imageToData( tex.image, ext ),
  262. original: tex
  263. } );
  264. }
  265. return texid;
  266. }
  267. // Process the given material into the material and effect libraries
  268. // Returns the material id
  269. function processMaterial( m ) {
  270. let matid = materialMap.get( m );
  271. if ( matid == null ) {
  272. matid = `Mat${ libraryEffects.length + 1 }`;
  273. let type = 'phong';
  274. if ( m.isMeshLambertMaterial === true ) {
  275. type = 'lambert';
  276. } else if ( m.isMeshBasicMaterial === true ) {
  277. type = 'constant';
  278. if ( m.map !== null ) {
  279. // The Collada spec does not support diffuse texture maps with the
  280. // constant shader type.
  281. // mrdoob/three.js#15469
  282. console.warn( 'ColladaExporter: Texture maps not supported with MeshBasicMaterial.' );
  283. }
  284. }
  285. const emissive = m.emissive ? m.emissive : new Color( 0, 0, 0 );
  286. const diffuse = m.color ? m.color : new Color( 0, 0, 0 );
  287. const specular = m.specular ? m.specular : new Color( 1, 1, 1 );
  288. const shininess = m.shininess || 0;
  289. const reflectivity = m.reflectivity || 0;
  290. emissive.convertLinearToSRGB();
  291. specular.convertLinearToSRGB();
  292. diffuse.convertLinearToSRGB();
  293. // Do not export and alpha map for the reasons mentioned in issue (#13792)
  294. // in three.js alpha maps are black and white, but collada expects the alpha
  295. // channel to specify the transparency
  296. let transparencyNode = '';
  297. if ( m.transparent === true ) {
  298. transparencyNode +=
  299. '<transparent>' +
  300. (
  301. m.map ?
  302. '<texture texture="diffuse-sampler"></texture>' :
  303. '<float>1</float>'
  304. ) +
  305. '</transparent>';
  306. if ( m.opacity < 1 ) {
  307. transparencyNode += `<transparency><float>${ m.opacity }</float></transparency>`;
  308. }
  309. }
  310. const techniqueNode = `<technique sid="common"><${ type }>` +
  311. '<emission>' +
  312. (
  313. m.emissiveMap ?
  314. '<texture texture="emissive-sampler" texcoord="TEXCOORD" />' :
  315. `<color sid="emission">${ emissive.r } ${ emissive.g } ${ emissive.b } 1</color>`
  316. ) +
  317. '</emission>' +
  318. (
  319. type !== 'constant' ?
  320. '<diffuse>' +
  321. (
  322. m.map ?
  323. '<texture texture="diffuse-sampler" texcoord="TEXCOORD" />' :
  324. `<color sid="diffuse">${ diffuse.r } ${ diffuse.g } ${ diffuse.b } 1</color>`
  325. ) +
  326. '</diffuse>'
  327. : ''
  328. ) +
  329. (
  330. type !== 'constant' ?
  331. '<bump>' +
  332. (
  333. m.normalMap ? '<texture texture="bump-sampler" texcoord="TEXCOORD" />' : ''
  334. ) +
  335. '</bump>'
  336. : ''
  337. ) +
  338. (
  339. type === 'phong' ?
  340. `<specular><color sid="specular">${ specular.r } ${ specular.g } ${ specular.b } 1</color></specular>` +
  341. '<shininess>' +
  342. (
  343. m.specularMap ?
  344. '<texture texture="specular-sampler" texcoord="TEXCOORD" />' :
  345. `<float sid="shininess">${ shininess }</float>`
  346. ) +
  347. '</shininess>'
  348. : ''
  349. ) +
  350. `<reflective><color>${ diffuse.r } ${ diffuse.g } ${ diffuse.b } 1</color></reflective>` +
  351. `<reflectivity><float>${ reflectivity }</float></reflectivity>` +
  352. transparencyNode +
  353. `</${ type }></technique>`;
  354. const effectnode =
  355. `<effect id="${ matid }-effect">` +
  356. '<profile_COMMON>' +
  357. (
  358. m.map ?
  359. '<newparam sid="diffuse-surface"><surface type="2D">' +
  360. `<init_from>${ processTexture( m.map ) }</init_from>` +
  361. '</surface></newparam>' +
  362. '<newparam sid="diffuse-sampler"><sampler2D><source>diffuse-surface</source></sampler2D></newparam>' :
  363. ''
  364. ) +
  365. (
  366. m.specularMap ?
  367. '<newparam sid="specular-surface"><surface type="2D">' +
  368. `<init_from>${ processTexture( m.specularMap ) }</init_from>` +
  369. '</surface></newparam>' +
  370. '<newparam sid="specular-sampler"><sampler2D><source>specular-surface</source></sampler2D></newparam>' :
  371. ''
  372. ) +
  373. (
  374. m.emissiveMap ?
  375. '<newparam sid="emissive-surface"><surface type="2D">' +
  376. `<init_from>${ processTexture( m.emissiveMap ) }</init_from>` +
  377. '</surface></newparam>' +
  378. '<newparam sid="emissive-sampler"><sampler2D><source>emissive-surface</source></sampler2D></newparam>' :
  379. ''
  380. ) +
  381. (
  382. m.normalMap ?
  383. '<newparam sid="bump-surface"><surface type="2D">' +
  384. `<init_from>${ processTexture( m.normalMap ) }</init_from>` +
  385. '</surface></newparam>' +
  386. '<newparam sid="bump-sampler"><sampler2D><source>bump-surface</source></sampler2D></newparam>' :
  387. ''
  388. ) +
  389. techniqueNode +
  390. (
  391. m.side === DoubleSide ?
  392. '<extra><technique profile="THREEJS"><double_sided sid="double_sided" type="int">1</double_sided></technique></extra>' :
  393. ''
  394. ) +
  395. '</profile_COMMON>' +
  396. '</effect>';
  397. const materialName = m.name ? ` name="${ m.name }"` : '';
  398. const materialNode = `<material id="${ matid }"${ materialName }><instance_effect url="#${ matid }-effect" /></material>`;
  399. libraryMaterials.push( materialNode );
  400. libraryEffects.push( effectnode );
  401. materialMap.set( m, matid );
  402. }
  403. return matid;
  404. }
  405. // Recursively process the object into a scene
  406. function processObject( o ) {
  407. let node = `<node name="${ o.name }">`;
  408. node += getTransform( o );
  409. if ( o.isMesh === true && o.geometry !== null ) {
  410. // function returns the id associated with the mesh and a "BufferGeometry" version
  411. // of the geometry in case it's not a geometry.
  412. const geomInfo = processGeometry( o.geometry );
  413. const meshid = geomInfo.meshid;
  414. const geometry = geomInfo.bufferGeometry;
  415. // ids of the materials to bind to the geometry
  416. let matids = null;
  417. let matidsArray;
  418. // get a list of materials to bind to the sub groups of the geometry.
  419. // If the amount of subgroups is greater than the materials, than reuse
  420. // the materials.
  421. const mat = o.material || new MeshBasicMaterial();
  422. const materials = Array.isArray( mat ) ? mat : [ mat ];
  423. if ( geometry.groups.length > materials.length ) {
  424. matidsArray = new Array( geometry.groups.length );
  425. } else {
  426. matidsArray = new Array( materials.length );
  427. }
  428. matids = matidsArray.fill().map( ( v, i ) => processMaterial( materials[ i % materials.length ] ) );
  429. node +=
  430. `<instance_geometry url="#${ meshid }">` +
  431. (
  432. matids.length > 0 ?
  433. '<bind_material><technique_common>' +
  434. matids.map( ( id, i ) =>
  435. `<instance_material symbol="MESH_MATERIAL_${ i }" target="#${ id }" >` +
  436. '<bind_vertex_input semantic="TEXCOORD" input_semantic="TEXCOORD" input_set="0" />' +
  437. '</instance_material>'
  438. ).join( '' ) +
  439. '</technique_common></bind_material>' :
  440. ''
  441. ) +
  442. '</instance_geometry>';
  443. }
  444. o.children.forEach( c => node += processObject( c ) );
  445. node += '</node>';
  446. return node;
  447. }
  448. const geometryInfo = new WeakMap();
  449. const materialMap = new WeakMap();
  450. const imageMap = new WeakMap();
  451. const textures = [];
  452. const libraryImages = [];
  453. const libraryGeometries = [];
  454. const libraryEffects = [];
  455. const libraryMaterials = [];
  456. const libraryVisualScenes = processObject( object );
  457. const specLink = version === '1.4.1' ? 'http://www.collada.org/2005/11/COLLADASchema' : 'https://www.khronos.org/collada/';
  458. let dae =
  459. '<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' +
  460. `<COLLADA xmlns="${ specLink }" version="${ version }">` +
  461. '<asset>' +
  462. (
  463. '<contributor>' +
  464. '<authoring_tool>three.js Collada Exporter</authoring_tool>' +
  465. ( options.author !== null ? `<author>${ options.author }</author>` : '' ) +
  466. '</contributor>' +
  467. `<created>${ ( new Date() ).toISOString() }</created>` +
  468. `<modified>${ ( new Date() ).toISOString() }</modified>` +
  469. ( options.unitName !== null ? `<unit name="${ options.unitName }" meter="${ options.unitMeter }" />` : '' ) +
  470. `<up_axis>${ options.upAxis }</up_axis>`
  471. ) +
  472. '</asset>';
  473. dae += `<library_images>${ libraryImages.join( '' ) }</library_images>`;
  474. dae += `<library_effects>${ libraryEffects.join( '' ) }</library_effects>`;
  475. dae += `<library_materials>${ libraryMaterials.join( '' ) }</library_materials>`;
  476. dae += `<library_geometries>${ libraryGeometries.join( '' ) }</library_geometries>`;
  477. dae += `<library_visual_scenes><visual_scene id="Scene" name="scene">${ libraryVisualScenes }</visual_scene></library_visual_scenes>`;
  478. dae += '<scene><instance_visual_scene url="#Scene"/></scene>';
  479. dae += '</COLLADA>';
  480. const res = {
  481. data: format( dae ),
  482. textures
  483. };
  484. if ( typeof onDone === 'function' ) {
  485. requestAnimationFrame( () => onDone( res ) );
  486. }
  487. return res;
  488. }
  489. }
  490. export { ColladaExporter };