ColladaExporter.js 17 KB

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