ColladaExporter.js 18 KB

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