ColladaExporter.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. ( function () {
  2. /**
  3. * https://github.com/gkjohnson/collada-exporter-js
  4. *
  5. * Usage:
  6. * const exporter = new ColladaExporter();
  7. *
  8. * const data = exporter.parse(mesh);
  9. *
  10. * Format Definition:
  11. * https://www.khronos.org/collada/
  12. */
  13. class ColladaExporter {
  14. parse( object, onDone, options = {} ) {
  15. options = Object.assign( {
  16. version: '1.4.1',
  17. author: null,
  18. textureDirectory: '',
  19. upAxis: 'Y_UP',
  20. unitName: null,
  21. unitMeter: null
  22. }, options );
  23. if ( options.upAxis.match( /^[XYZ]_UP$/ ) === null ) {
  24. console.error( 'ColladaExporter: Invalid upAxis: valid values are X_UP, Y_UP or Z_UP.' );
  25. return null;
  26. }
  27. if ( options.unitName !== null && options.unitMeter === null ) {
  28. console.error( 'ColladaExporter: unitMeter needs to be specified if unitName is specified.' );
  29. return null;
  30. }
  31. if ( options.unitMeter !== null && options.unitName === null ) {
  32. console.error( 'ColladaExporter: unitName needs to be specified if unitMeter is specified.' );
  33. return null;
  34. }
  35. if ( options.textureDirectory !== '' ) {
  36. options.textureDirectory = `${options.textureDirectory}/`.replace( /\\/g, '/' ).replace( /\/+/g, '/' );
  37. }
  38. const 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. const IS_END_TAG = /^<\//;
  46. const IS_SELF_CLOSING = /(\?>$)|(\/>$)/;
  47. const HAS_TEXT = /<[^>]+>[^<]*<\/[^<]+>/;
  48. const pad = ( ch, num ) => num > 0 ? ch + pad( ch, num - 1 ) : '';
  49. let tagnum = 0;
  50. return urdf.match( /(<[^>]+>[^<]+<\/[^<]+>)|(<[^>]+>)/g ).map( tag => {
  51. if ( ! HAS_TEXT.test( tag ) && ! IS_SELF_CLOSING.test( tag ) && IS_END_TAG.test( tag ) ) {
  52. tagnum --;
  53. }
  54. const res = `${pad( ' ', tagnum )}${tag}`;
  55. if ( ! HAS_TEXT.test( tag ) && ! IS_SELF_CLOSING.test( tag ) && ! IS_END_TAG.test( tag ) ) {
  56. tagnum ++;
  57. }
  58. return res;
  59. } ).join( '\n' );
  60. }
  61. // Convert an image into a png format for saving
  62. function base64ToBuffer( str ) {
  63. const b = atob( str );
  64. const buf = new Uint8Array( b.length );
  65. for ( let i = 0, l = buf.length; i < l; i ++ ) {
  66. buf[ i ] = b.charCodeAt( i );
  67. }
  68. return buf;
  69. }
  70. let canvas, ctx;
  71. function imageToData( image, ext ) {
  72. canvas = canvas || document.createElement( 'canvas' );
  73. ctx = ctx || canvas.getContext( '2d' );
  74. canvas.width = image.width;
  75. canvas.height = image.height;
  76. ctx.drawImage( image, 0, 0 );
  77. // Get the base64 encoded data
  78. const base64data = canvas.toDataURL( `image/${ext}`, 1 ).replace( /^data:image\/(png|jpg);base64,/, '' );
  79. // Convert to a uint8 array
  80. return base64ToBuffer( base64data );
  81. }
  82. // gets the attribute array. Generate a new array if the attribute is interleaved
  83. const getFuncs = [ 'getX', 'getY', 'getZ', 'getW' ];
  84. const tempColor = new THREE.Color();
  85. function attrBufferToArray( attr, isColor = false ) {
  86. if ( isColor ) {
  87. // convert the colors to srgb before export
  88. // colors are always written as floats
  89. const arr = new Float32Array( attr.count * 3 );
  90. for ( let i = 0, l = attr.count; i < l; i ++ ) {
  91. tempColor.fromBufferAttribute( attr, i ).convertLinearToSRGB();
  92. arr[ 3 * i + 0 ] = tempColor.r;
  93. arr[ 3 * i + 1 ] = tempColor.g;
  94. arr[ 3 * i + 2 ] = tempColor.b;
  95. }
  96. return arr;
  97. } else if ( attr.isInterleavedBufferAttribute ) {
  98. // use the typed array constructor to save on memory
  99. const arr = new attr.array.constructor( attr.count * attr.itemSize );
  100. const size = attr.itemSize;
  101. for ( let i = 0, l = attr.count; i < l; i ++ ) {
  102. for ( let j = 0; j < size; j ++ ) {
  103. arr[ i * size + j ] = attr[ getFuncs[ j ] ]( i );
  104. }
  105. }
  106. return arr;
  107. } else {
  108. return attr.array;
  109. }
  110. }
  111. // Returns an array of the same type starting at the `st` index,
  112. // and `ct` length
  113. function subArray( arr, st, ct ) {
  114. if ( Array.isArray( arr ) ) return arr.slice( st, st + ct ); else return new arr.constructor( arr.buffer, st * arr.BYTES_PER_ELEMENT, ct );
  115. }
  116. // Returns the string for a geometry's attribute
  117. function getAttribute( attr, name, params, type, isColor = false ) {
  118. const array = attrBufferToArray( attr, isColor );
  119. const res = `<source id="${name}">` + `<float_array id="${name}-array" count="${array.length}">` + array.join( ' ' ) + '</float_array>' + '<technique_common>' + `<accessor source="#${name}-array" count="${Math.floor( array.length / attr.itemSize )}" stride="${attr.itemSize}">` + params.map( n => `<param name="${n}" type="${type}" />` ).join( '' ) + '</accessor>' + '</technique_common>' + '</source>';
  120. return res;
  121. }
  122. // Returns the string for a node's transform information
  123. let transMat;
  124. function getTransform( o ) {
  125. // ensure the object's matrix is up to date
  126. // before saving the transform
  127. o.updateMatrix();
  128. transMat = transMat || new THREE.Matrix4();
  129. transMat.copy( o.matrix );
  130. transMat.transpose();
  131. return `<matrix>${transMat.toArray().join( ' ' )}</matrix>`;
  132. }
  133. // Process the given piece of geometry into the geometry library
  134. // Returns the mesh id
  135. function processGeometry( bufferGeometry ) {
  136. let info = geometryInfo.get( bufferGeometry );
  137. if ( ! info ) {
  138. const meshid = `Mesh${libraryGeometries.length + 1}`;
  139. const indexCount = bufferGeometry.index ? bufferGeometry.index.count * bufferGeometry.index.itemSize : bufferGeometry.attributes.position.count;
  140. const groups = bufferGeometry.groups != null && bufferGeometry.groups.length !== 0 ? bufferGeometry.groups : [ {
  141. start: 0,
  142. count: indexCount,
  143. materialIndex: 0
  144. } ];
  145. const gname = bufferGeometry.name ? ` name="${bufferGeometry.name}"` : '';
  146. let gnode = `<geometry id="${meshid}"${gname}><mesh>`;
  147. // define the geometry node and the vertices for the geometry
  148. const posName = `${meshid}-position`;
  149. const 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. let triangleInputs = `<input semantic="VERTEX" source="#${vertName}" offset="0" />`;
  158. if ( 'normal' in bufferGeometry.attributes ) {
  159. const 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. const 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. const 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. // colors are always written as floats
  178. const colName = `${meshid}-color`;
  179. gnode += getAttribute( bufferGeometry.attributes.color, colName, [ 'R', 'G', 'B' ], 'float', true );
  180. triangleInputs += `<input semantic="COLOR" source="#${colName}" offset="0" />`;
  181. }
  182. let indexArray = null;
  183. if ( bufferGeometry.index ) {
  184. indexArray = attrBufferToArray( bufferGeometry.index );
  185. } else {
  186. indexArray = new Array( indexCount );
  187. for ( let i = 0, l = indexArray.length; i < l; i ++ ) indexArray[ i ] = i;
  188. }
  189. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  190. const group = groups[ i ];
  191. const subarr = subArray( indexArray, group.start, group.count );
  192. const polycount = subarr.length / 3;
  193. gnode += `<triangles material="MESH_MATERIAL_${group.materialIndex}" count="${polycount}">`;
  194. gnode += triangleInputs;
  195. gnode += `<p>${subarr.join( ' ' )}</p>`;
  196. gnode += '</triangles>';
  197. }
  198. gnode += '</mesh></geometry>';
  199. libraryGeometries.push( gnode );
  200. info = {
  201. meshid: meshid,
  202. bufferGeometry: bufferGeometry
  203. };
  204. geometryInfo.set( bufferGeometry, 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. let texid = imageMap.get( tex );
  212. if ( texid == null ) {
  213. texid = `image-${libraryImages.length + 1}`;
  214. const ext = 'png';
  215. const name = tex.name || texid;
  216. let 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. let matid = materialMap.get( m );
  240. if ( matid == null ) {
  241. matid = `Mat${libraryEffects.length + 1}`;
  242. let type = 'phong';
  243. if ( m.isMeshLambertMaterial === true ) {
  244. type = 'lambert';
  245. } else if ( m.isMeshBasicMaterial === true ) {
  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 THREE.MeshBasicMaterial.' );
  252. }
  253. }
  254. const emissive = m.emissive ? m.emissive : new THREE.Color( 0, 0, 0 );
  255. const diffuse = m.color ? m.color : new THREE.Color( 0, 0, 0 );
  256. const specular = m.specular ? m.specular : new THREE.Color( 1, 1, 1 );
  257. const shininess = m.shininess || 0;
  258. const reflectivity = m.reflectivity || 0;
  259. emissive.convertLinearToSRGB();
  260. specular.convertLinearToSRGB();
  261. diffuse.convertLinearToSRGB();
  262. // Do not export and alpha map for the reasons mentioned in issue (#13792)
  263. // in three.js alpha maps are black and white, but collada expects the alpha
  264. // channel to specify the transparency
  265. let transparencyNode = '';
  266. if ( m.transparent === true ) {
  267. transparencyNode += '<transparent>' + ( m.map ? '<texture texture="diffuse-sampler"></texture>' : '<float>1</float>' ) + '</transparent>';
  268. if ( m.opacity < 1 ) {
  269. transparencyNode += `<transparency><float>${m.opacity}</float></transparency>`;
  270. }
  271. }
  272. const techniqueNode = `<technique sid="common"><${type}>` + '<emission>' + ( m.emissiveMap ? '<texture texture="emissive-sampler" texcoord="TEXCOORD" />' : `<color sid="emission">${emissive.r} ${emissive.g} ${emissive.b} 1</color>` ) + '</emission>' + ( type !== 'constant' ? '<diffuse>' + ( m.map ? '<texture texture="diffuse-sampler" texcoord="TEXCOORD" />' : `<color sid="diffuse">${diffuse.r} ${diffuse.g} ${diffuse.b} 1</color>` ) + '</diffuse>' : '' ) + ( type !== 'constant' ? '<bump>' + ( m.normalMap ? '<texture texture="bump-sampler" texcoord="TEXCOORD" />' : '' ) + '</bump>' : '' ) + ( type === 'phong' ? `<specular><color sid="specular">${specular.r} ${specular.g} ${specular.b} 1</color></specular>` + '<shininess>' + ( m.specularMap ? '<texture texture="specular-sampler" texcoord="TEXCOORD" />' : `<float sid="shininess">${shininess}</float>` ) + '</shininess>' : '' ) + `<reflective><color>${diffuse.r} ${diffuse.g} ${diffuse.b} 1</color></reflective>` + `<reflectivity><float>${reflectivity}</float></reflectivity>` + transparencyNode + `</${type}></technique>`;
  273. const effectnode = `<effect id="${matid}-effect">` + '<profile_COMMON>' + ( m.map ? '<newparam sid="diffuse-surface"><surface type="2D">' + `<init_from>${processTexture( m.map )}</init_from>` + '</surface></newparam>' + '<newparam sid="diffuse-sampler"><sampler2D><source>diffuse-surface</source></sampler2D></newparam>' : '' ) + ( m.specularMap ? '<newparam sid="specular-surface"><surface type="2D">' + `<init_from>${processTexture( m.specularMap )}</init_from>` + '</surface></newparam>' + '<newparam sid="specular-sampler"><sampler2D><source>specular-surface</source></sampler2D></newparam>' : '' ) + ( m.emissiveMap ? '<newparam sid="emissive-surface"><surface type="2D">' + `<init_from>${processTexture( m.emissiveMap )}</init_from>` + '</surface></newparam>' + '<newparam sid="emissive-sampler"><sampler2D><source>emissive-surface</source></sampler2D></newparam>' : '' ) + ( m.normalMap ? '<newparam sid="bump-surface"><surface type="2D">' + `<init_from>${processTexture( m.normalMap )}</init_from>` + '</surface></newparam>' + '<newparam sid="bump-sampler"><sampler2D><source>bump-surface</source></sampler2D></newparam>' : '' ) + techniqueNode + ( m.side === THREE.DoubleSide ? '<extra><technique profile="THREEJS"><double_sided sid="double_sided" type="int">1</double_sided></technique></extra>' : '' ) + '</profile_COMMON>' + '</effect>';
  274. const materialName = m.name ? ` name="${m.name}"` : '';
  275. const materialNode = `<material id="${matid}"${materialName}><instance_effect url="#${matid}-effect" /></material>`;
  276. libraryMaterials.push( materialNode );
  277. libraryEffects.push( effectnode );
  278. materialMap.set( m, matid );
  279. }
  280. return matid;
  281. }
  282. // Recursively process the object into a scene
  283. function processObject( o ) {
  284. let node = `<node name="${o.name}">`;
  285. node += getTransform( o );
  286. if ( o.isMesh === true && o.geometry !== null ) {
  287. // function returns the id associated with the mesh and a "BufferGeometry" version
  288. // of the geometry in case it's not a geometry.
  289. const geomInfo = processGeometry( o.geometry );
  290. const meshid = geomInfo.meshid;
  291. const geometry = geomInfo.bufferGeometry;
  292. // ids of the materials to bind to the geometry
  293. let matids = null;
  294. let matidsArray;
  295. // get a list of materials to bind to the sub groups of the geometry.
  296. // If the amount of subgroups is greater than the materials, than reuse
  297. // the materials.
  298. const mat = o.material || new THREE.MeshBasicMaterial();
  299. const materials = Array.isArray( mat ) ? mat : [ mat ];
  300. if ( geometry.groups.length > materials.length ) {
  301. matidsArray = new Array( geometry.groups.length );
  302. } else {
  303. matidsArray = new Array( materials.length );
  304. }
  305. matids = matidsArray.fill().map( ( v, i ) => processMaterial( materials[ i % materials.length ] ) );
  306. node += `<instance_geometry url="#${meshid}">` + ( matids.length > 0 ? '<bind_material><technique_common>' + matids.map( ( id, i ) => `<instance_material symbol="MESH_MATERIAL_${i}" target="#${id}" >` + '<bind_vertex_input semantic="TEXCOORD" input_semantic="TEXCOORD" input_set="0" />' + '</instance_material>' ).join( '' ) + '</technique_common></bind_material>' : '' ) + '</instance_geometry>';
  307. }
  308. o.children.forEach( c => node += processObject( c ) );
  309. node += '</node>';
  310. return node;
  311. }
  312. const geometryInfo = new WeakMap();
  313. const materialMap = new WeakMap();
  314. const imageMap = new WeakMap();
  315. const textures = [];
  316. const libraryImages = [];
  317. const libraryGeometries = [];
  318. const libraryEffects = [];
  319. const libraryMaterials = [];
  320. const libraryVisualScenes = processObject( object );
  321. const specLink = version === '1.4.1' ? 'http://www.collada.org/2005/11/COLLADASchema' : 'https://www.khronos.org/collada/';
  322. let dae = '<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + `<COLLADA xmlns="${specLink}" version="${version}">` + '<asset>' + ( '<contributor>' + '<authoring_tool>three.js Collada Exporter</authoring_tool>' + ( options.author !== null ? `<author>${options.author}</author>` : '' ) + '</contributor>' + `<created>${new Date().toISOString()}</created>` + `<modified>${new Date().toISOString()}</modified>` + ( options.unitName !== null ? `<unit name="${options.unitName}" meter="${options.unitMeter}" />` : '' ) + `<up_axis>${options.upAxis}</up_axis>` ) + '</asset>';
  323. dae += `<library_images>${libraryImages.join( '' )}</library_images>`;
  324. dae += `<library_effects>${libraryEffects.join( '' )}</library_effects>`;
  325. dae += `<library_materials>${libraryMaterials.join( '' )}</library_materials>`;
  326. dae += `<library_geometries>${libraryGeometries.join( '' )}</library_geometries>`;
  327. dae += `<library_visual_scenes><visual_scene id="Scene" name="scene">${libraryVisualScenes}</visual_scene></library_visual_scenes>`;
  328. dae += '<scene><instance_visual_scene url="#Scene"/></scene>';
  329. dae += '</COLLADA>';
  330. const res = {
  331. data: format( dae ),
  332. textures
  333. };
  334. if ( typeof onDone === 'function' ) {
  335. requestAnimationFrame( () => onDone( res ) );
  336. }
  337. return res;
  338. }
  339. }
  340. THREE.ColladaExporter = ColladaExporter;
  341. } )();