ColladaExporter.js 16 KB

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