ColladaExporter.js 16 KB

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