ColladaExporter.js 18 KB

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