ColladaExporter.js 16 KB

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