2
0

ColladaExporter.js 17 KB

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