ColladaExporter.js 18 KB

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