ColladaExporter.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  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 gnode = `<geometry id="${ meshid }" name="${ g.name }"><mesh>`;
  157. // define the geometry node and the vertices for the geometry
  158. var posName = `${ meshid }-position`;
  159. var vertName = `${ meshid }-vertices`;
  160. gnode += getAttribute( bufferGeometry.attributes.position, posName, [ 'X', 'Y', 'Z' ], 'float' );
  161. gnode += `<vertices id="${ vertName }"><input semantic="POSITION" source="#${ posName }" /></vertices>`;
  162. // NOTE: We're not optimizing the attribute arrays here, so they're all the same length and
  163. // can therefore share the same triangle indices. However, MeshLab seems to have trouble opening
  164. // models with attributes that share an offset.
  165. // MeshLab Bug#424: https://sourceforge.net/p/meshlab/bugs/424/
  166. // serialize normals
  167. var triangleInputs = `<input semantic="VERTEX" source="#${ vertName }" offset="0" />`;
  168. if ( 'normal' in bufferGeometry.attributes ) {
  169. var normName = `${ meshid }-normal`;
  170. gnode += getAttribute( bufferGeometry.attributes.normal, normName, [ 'X', 'Y', 'Z' ], 'float' );
  171. triangleInputs += `<input semantic="NORMAL" source="#${ normName }" offset="0" />`;
  172. }
  173. // serialize uvs
  174. if ( 'uv' in bufferGeometry.attributes ) {
  175. var uvName = `${ meshid }-texcoord`;
  176. gnode += getAttribute( bufferGeometry.attributes.uv, uvName, [ 'S', 'T' ], 'float' );
  177. triangleInputs += `<input semantic="TEXCOORD" source="#${ uvName }" offset="0" set="0" />`;
  178. }
  179. // serialize colors
  180. if ( 'color' in bufferGeometry.attributes ) {
  181. var colName = `${ meshid }-color`;
  182. gnode += getAttribute( bufferGeometry.attributes.color, colName, [ 'X', 'Y', 'Z' ], 'uint8' );
  183. triangleInputs += `<input semantic="COLOR" source="#${ colName }" offset="0" />`;
  184. }
  185. var indexArray = null;
  186. if ( bufferGeometry.index ) {
  187. indexArray = attrBufferToArray( bufferGeometry.index );
  188. } else {
  189. indexArray = new Array( indexCount );
  190. for ( var i = 0, l = indexArray.length; i < l; i ++ ) indexArray[ i ] = i;
  191. }
  192. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  193. var group = groups[ i ];
  194. var subarr = subArray( indexArray, group.start, group.count );
  195. var polycount = subarr.length / 3;
  196. gnode += `<triangles material="MESH_MATERIAL_${ group.materialIndex }" count="${ polycount }">`;
  197. gnode += triangleInputs;
  198. gnode += `<p>${ subarr.join( ' ' ) }</p>`;
  199. gnode += '</triangles>';
  200. }
  201. gnode += `</mesh></geometry>`;
  202. libraryGeometries.push( gnode );
  203. info = { meshid: meshid, bufferGeometry: bufferGeometry };
  204. geometryInfo.set( g, info );
  205. }
  206. return info;
  207. }
  208. // Process the given texture into the image library
  209. // Returns the image library
  210. function processTexture( tex ) {
  211. var texid = imageMap.get( tex );
  212. if ( texid == null ) {
  213. texid = `image-${ libraryImages.length + 1 }`;
  214. var ext = 'png';
  215. var name = tex.name || texid;
  216. var imageNode = `<image id="${ texid }" name="${ name }">`;
  217. if ( version === '1.5.0' ) {
  218. imageNode += `<init_from><ref>${ options.textureDirectory }${ name }.${ ext }</ref></init_from>`;
  219. } else {
  220. // version image node 1.4.1
  221. imageNode += `<init_from>${ options.textureDirectory }${ name }.${ ext }</init_from>`;
  222. }
  223. imageNode += '</image>';
  224. libraryImages.push( imageNode );
  225. imageMap.set( tex, texid );
  226. textures.push( {
  227. directory: options.textureDirectory,
  228. name,
  229. ext,
  230. data: imageToData( tex.image, ext ),
  231. original: tex
  232. } );
  233. }
  234. return texid;
  235. }
  236. // Process the given material into the material and effect libraries
  237. // Returns the material id
  238. function processMaterial( m ) {
  239. var matid = materialMap.get( m );
  240. if ( matid == null ) {
  241. matid = `Mat${ libraryEffects.length + 1 }`;
  242. var type = 'phong';
  243. if ( m instanceof MeshLambertMaterial ) {
  244. type = 'lambert';
  245. } else if ( m instanceof MeshBasicMaterial ) {
  246. type = 'constant';
  247. if ( m.map !== null ) {
  248. // The Collada spec does not support diffuse texture maps with the
  249. // constant shader type.
  250. // mrdoob/three.js#15469
  251. console.warn( 'ColladaExporter: Texture maps not supported with MeshBasicMaterial.' );
  252. }
  253. }
  254. var emissive = m.emissive ? m.emissive : new Color( 0, 0, 0 );
  255. var diffuse = m.color ? m.color : new Color( 0, 0, 0 );
  256. var specular = m.specular ? m.specular : new Color( 1, 1, 1 );
  257. var shininess = m.shininess || 0;
  258. var reflectivity = m.reflectivity || 0;
  259. // Do not export and alpha map for the reasons mentioned in issue (#13792)
  260. // in three.js alpha maps are black and white, but collada expects the alpha
  261. // channel to specify the transparency
  262. var transparencyNode = '';
  263. if ( m.transparent === true ) {
  264. transparencyNode +=
  265. `<transparent>` +
  266. (
  267. m.map ?
  268. `<texture texture="diffuse-sampler"></texture>` :
  269. '<float>1</float>'
  270. ) +
  271. '</transparent>';
  272. if ( m.opacity < 1 ) {
  273. transparencyNode += `<transparency><float>${ m.opacity }</float></transparency>`;
  274. }
  275. }
  276. var techniqueNode = `<technique sid="common"><${ type }>` +
  277. '<emission>' +
  278. (
  279. m.emissiveMap ?
  280. '<texture texture="emissive-sampler" texcoord="TEXCOORD" />' :
  281. `<color sid="emission">${ emissive.r } ${ emissive.g } ${ emissive.b } 1</color>`
  282. ) +
  283. '</emission>' +
  284. (
  285. type !== 'constant' ?
  286. '<diffuse>' +
  287. (
  288. m.map ?
  289. '<texture texture="diffuse-sampler" texcoord="TEXCOORD" />' :
  290. `<color sid="diffuse">${ diffuse.r } ${ diffuse.g } ${ diffuse.b } 1</color>`
  291. ) +
  292. '</diffuse>'
  293. : ''
  294. ) +
  295. (
  296. type === 'phong' ?
  297. `<specular><color sid="specular">${ specular.r } ${ specular.g } ${ specular.b } 1</color></specular>` +
  298. '<shininess>' +
  299. (
  300. m.specularMap ?
  301. '<texture texture="specular-sampler" texcoord="TEXCOORD" />' :
  302. `<float sid="shininess">${ shininess }</float>`
  303. ) +
  304. '</shininess>'
  305. : ''
  306. ) +
  307. `<reflective><color>${ diffuse.r } ${ diffuse.g } ${ diffuse.b } 1</color></reflective>` +
  308. `<reflectivity><float>${ reflectivity }</float></reflectivity>` +
  309. transparencyNode +
  310. `</${ type }></technique>`;
  311. var effectnode =
  312. `<effect id="${ matid }-effect">` +
  313. '<profile_COMMON>' +
  314. (
  315. m.map ?
  316. '<newparam sid="diffuse-surface"><surface type="2D">' +
  317. `<init_from>${ processTexture( m.map ) }</init_from>` +
  318. '</surface></newparam>' +
  319. '<newparam sid="diffuse-sampler"><sampler2D><source>diffuse-surface</source></sampler2D></newparam>' :
  320. ''
  321. ) +
  322. (
  323. m.specularMap ?
  324. '<newparam sid="specular-surface"><surface type="2D">' +
  325. `<init_from>${ processTexture( m.specularMap ) }</init_from>` +
  326. '</surface></newparam>' +
  327. '<newparam sid="specular-sampler"><sampler2D><source>specular-surface</source></sampler2D></newparam>' :
  328. ''
  329. ) +
  330. (
  331. m.emissiveMap ?
  332. '<newparam sid="emissive-surface"><surface type="2D">' +
  333. `<init_from>${ processTexture( m.emissiveMap ) }</init_from>` +
  334. '</surface></newparam>' +
  335. '<newparam sid="emissive-sampler"><sampler2D><source>emissive-surface</source></sampler2D></newparam>' :
  336. ''
  337. ) +
  338. techniqueNode +
  339. (
  340. m.side === DoubleSide ?
  341. `<extra><technique><double_sided sid="double_sided" type="int">1</double_sided></technique></extra>` :
  342. ''
  343. ) +
  344. '</profile_COMMON>' +
  345. '</effect>';
  346. libraryMaterials.push( `<material id="${ matid }" name="${ m.name }"><instance_effect url="#${ matid }-effect" /></material>` );
  347. libraryEffects.push( effectnode );
  348. materialMap.set( m, matid );
  349. }
  350. return matid;
  351. }
  352. // Recursively process the object into a scene
  353. function processObject( o ) {
  354. var node = `<node name="${ o.name }">`;
  355. node += getTransform( o );
  356. if ( o instanceof Mesh && o.geometry != null ) {
  357. // function returns the id associated with the mesh and a "BufferGeometry" version
  358. // of the geometry in case it's not a geometry.
  359. var geomInfo = processGeometry( o.geometry );
  360. var meshid = geomInfo.meshid;
  361. var geometry = geomInfo.bufferGeometry;
  362. // ids of the materials to bind to the geometry
  363. var matids = null;
  364. var matidsArray = [];
  365. // get a list of materials to bind to the sub groups of the geometry.
  366. // If the amount of subgroups is greater than the materials, than reuse
  367. // the materials.
  368. var mat = o.material || new MeshBasicMaterial();
  369. var materials = Array.isArray( mat ) ? mat : [ mat ];
  370. if ( geometry.groups.length > materials.length ) {
  371. matidsArray = new Array( geometry.groups.length );
  372. } else {
  373. matidsArray = new Array( materials.length );
  374. }
  375. matids = matidsArray.fill()
  376. .map( ( v, i ) => processMaterial( materials[ i % materials.length ] ) );
  377. node +=
  378. `<instance_geometry url="#${ meshid }">` +
  379. (
  380. matids != null ?
  381. '<bind_material><technique_common>' +
  382. matids.map( ( id, i ) =>
  383. `<instance_material symbol="MESH_MATERIAL_${ i }" target="#${ id }" >` +
  384. '<bind_vertex_input semantic="TEXCOORD" input_semantic="TEXCOORD" input_set="0" />' +
  385. '</instance_material>'
  386. ).join( '' ) +
  387. '</technique_common></bind_material>' :
  388. ''
  389. ) +
  390. '</instance_geometry>';
  391. }
  392. o.children.forEach( c => node += processObject( c ) );
  393. node += '</node>';
  394. return node;
  395. }
  396. var geometryInfo = new WeakMap();
  397. var materialMap = new WeakMap();
  398. var imageMap = new WeakMap();
  399. var textures = [];
  400. var libraryImages = [];
  401. var libraryGeometries = [];
  402. var libraryEffects = [];
  403. var libraryMaterials = [];
  404. var libraryVisualScenes = processObject( object );
  405. var specLink = version === '1.4.1' ? 'http://www.collada.org/2005/11/COLLADASchema' : 'https://www.khronos.org/collada/';
  406. var dae =
  407. '<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' +
  408. `<COLLADA xmlns="${ specLink }" version="${ version }">` +
  409. '<asset>' +
  410. (
  411. '<contributor>' +
  412. '<authoring_tool>three.js Collada Exporter</authoring_tool>' +
  413. ( options.author !== null ? `<author>${ options.author }</author>` : '' ) +
  414. '</contributor>' +
  415. `<created>${ ( new Date() ).toISOString() }</created>` +
  416. `<modified>${ ( new Date() ).toISOString() }</modified>` +
  417. '<up_axis>Y_UP</up_axis>'
  418. ) +
  419. '</asset>';
  420. dae += `<library_images>${ libraryImages.join( '' ) }</library_images>`;
  421. dae += `<library_effects>${ libraryEffects.join( '' ) }</library_effects>`;
  422. dae += `<library_materials>${ libraryMaterials.join( '' ) }</library_materials>`;
  423. dae += `<library_geometries>${ libraryGeometries.join( '' ) }</library_geometries>`;
  424. dae += `<library_visual_scenes><visual_scene id="Scene" name="scene">${ libraryVisualScenes }</visual_scene></library_visual_scenes>`;
  425. dae += '<scene><instance_visual_scene url="#Scene"/></scene>';
  426. dae += '</COLLADA>';
  427. var res = {
  428. data: format( dae ),
  429. textures
  430. };
  431. if ( typeof onDone === 'function' ) {
  432. requestAnimationFrame( () => onDone( res ) );
  433. }
  434. return res;
  435. }
  436. };
  437. export { ColladaExporter };