2
0

ColladaExporter.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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. } // Convert the urdf xml into a well-formatted, indented format
  43. function format( urdf ) {
  44. const IS_END_TAG = /^<\//;
  45. const IS_SELF_CLOSING = /(\?>$)|(\/>$)/;
  46. const HAS_TEXT = /<[^>]+>[^<]*<\/[^<]+>/;
  47. const pad = ( ch, num ) => num > 0 ? ch + pad( ch, num - 1 ) : '';
  48. let tagnum = 0;
  49. return urdf.match( /(<[^>]+>[^<]+<\/[^<]+>)|(<[^>]+>)/g ).map( tag => {
  50. if ( ! HAS_TEXT.test( tag ) && ! IS_SELF_CLOSING.test( tag ) && IS_END_TAG.test( tag ) ) {
  51. tagnum --;
  52. }
  53. const res = `${pad( ' ', tagnum )}${tag}`;
  54. if ( ! HAS_TEXT.test( tag ) && ! IS_SELF_CLOSING.test( tag ) && ! IS_END_TAG.test( tag ) ) {
  55. tagnum ++;
  56. }
  57. return res;
  58. } ).join( '\n' );
  59. } // Convert an image into a png format for saving
  60. function base64ToBuffer( str ) {
  61. const b = atob( str );
  62. const buf = new Uint8Array( b.length );
  63. for ( let i = 0, l = buf.length; i < l; i ++ ) {
  64. buf[ i ] = b.charCodeAt( i );
  65. }
  66. return buf;
  67. }
  68. let canvas, ctx;
  69. function imageToData( image, ext ) {
  70. canvas = canvas || document.createElement( 'canvas' );
  71. ctx = ctx || canvas.getContext( '2d' );
  72. canvas.width = image.width;
  73. canvas.height = image.height;
  74. ctx.drawImage( image, 0, 0 ); // Get the base64 encoded data
  75. const base64data = canvas.toDataURL( `image/${ext}`, 1 ).replace( /^data:image\/(png|jpg);base64,/, '' ); // Convert to a uint8 array
  76. return base64ToBuffer( base64data );
  77. } // gets the attribute array. Generate a new array if the attribute is interleaved
  78. const getFuncs = [ 'getX', 'getY', 'getZ', 'getW' ];
  79. const tempColor = new THREE.Color();
  80. function attrBufferToArray( attr, isColor = false ) {
  81. if ( isColor ) {
  82. // convert the colors to srgb before export
  83. // colors are always written as floats
  84. const arr = new Float32Array( attr.count * 3 );
  85. for ( let i = 0, l = attr.count; i < l; i ++ ) {
  86. tempColor.fromBufferAttribute( attr, i ).convertLinearToSRGB();
  87. arr[ 3 * i + 0 ] = tempColor.r;
  88. arr[ 3 * i + 1 ] = tempColor.g;
  89. arr[ 3 * i + 2 ] = tempColor.b;
  90. }
  91. return arr;
  92. } else if ( attr.isInterleavedBufferAttribute ) {
  93. // use the typed array constructor to save on memory
  94. const arr = new attr.array.constructor( attr.count * attr.itemSize );
  95. const size = attr.itemSize;
  96. for ( let i = 0, l = attr.count; i < l; i ++ ) {
  97. for ( let j = 0; j < size; j ++ ) {
  98. arr[ i * size + j ] = attr[ getFuncs[ j ] ]( i );
  99. }
  100. }
  101. return arr;
  102. } else {
  103. return attr.array;
  104. }
  105. } // Returns an array of the same type starting at the `st` index,
  106. // and `ct` length
  107. function subArray( arr, st, ct ) {
  108. if ( Array.isArray( arr ) ) return arr.slice( st, st + ct ); else return new arr.constructor( arr.buffer, st * arr.BYTES_PER_ELEMENT, ct );
  109. } // Returns the string for a geometry's attribute
  110. function getAttribute( attr, name, params, type, isColor = false ) {
  111. const array = attrBufferToArray( attr, isColor );
  112. 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>';
  113. return res;
  114. } // Returns the string for a node's transform information
  115. let transMat;
  116. function getTransform( o ) {
  117. // ensure the object's matrix is up to date
  118. // before saving the transform
  119. o.updateMatrix();
  120. transMat = transMat || new THREE.Matrix4();
  121. transMat.copy( o.matrix );
  122. transMat.transpose();
  123. return `<matrix>${transMat.toArray().join( ' ' )}</matrix>`;
  124. } // Process the given piece of geometry into the geometry library
  125. // Returns the mesh id
  126. function processGeometry( g ) {
  127. let info = geometryInfo.get( g );
  128. if ( ! info ) {
  129. // convert the geometry to bufferGeometry if it isn't already
  130. const bufferGeometry = g;
  131. if ( bufferGeometry.isBufferGeometry !== true ) {
  132. throw new Error( 'THREE.ColladaExporter: Geometry is not of type THREE.BufferGeometry.' );
  133. }
  134. const meshid = `Mesh${libraryGeometries.length + 1}`;
  135. const indexCount = bufferGeometry.index ? bufferGeometry.index.count * bufferGeometry.index.itemSize : bufferGeometry.attributes.position.count;
  136. const groups = bufferGeometry.groups != null && bufferGeometry.groups.length !== 0 ? bufferGeometry.groups : [ {
  137. start: 0,
  138. count: indexCount,
  139. materialIndex: 0
  140. } ];
  141. const gname = g.name ? ` name="${g.name}"` : '';
  142. let gnode = `<geometry id="${meshid}"${gname}><mesh>`; // define the geometry node and the vertices for the geometry
  143. const posName = `${meshid}-position`;
  144. const vertName = `${meshid}-vertices`;
  145. gnode += getAttribute( bufferGeometry.attributes.position, posName, [ 'X', 'Y', 'Z' ], 'float' );
  146. gnode += `<vertices id="${vertName}"><input semantic="POSITION" source="#${posName}" /></vertices>`; // NOTE: We're not optimizing the attribute arrays here, so they're all the same length and
  147. // can therefore share the same triangle indices. However, MeshLab seems to have trouble opening
  148. // models with attributes that share an offset.
  149. // MeshLab Bug#424: https://sourceforge.net/p/meshlab/bugs/424/
  150. // serialize normals
  151. let triangleInputs = `<input semantic="VERTEX" source="#${vertName}" offset="0" />`;
  152. if ( 'normal' in bufferGeometry.attributes ) {
  153. const normName = `${meshid}-normal`;
  154. gnode += getAttribute( bufferGeometry.attributes.normal, normName, [ 'X', 'Y', 'Z' ], 'float' );
  155. triangleInputs += `<input semantic="NORMAL" source="#${normName}" offset="0" />`;
  156. } // serialize uvs
  157. if ( 'uv' in bufferGeometry.attributes ) {
  158. const uvName = `${meshid}-texcoord`;
  159. gnode += getAttribute( bufferGeometry.attributes.uv, uvName, [ 'S', 'T' ], 'float' );
  160. triangleInputs += `<input semantic="TEXCOORD" source="#${uvName}" offset="0" set="0" />`;
  161. } // serialize lightmap uvs
  162. if ( 'uv2' in bufferGeometry.attributes ) {
  163. const uvName = `${meshid}-texcoord2`;
  164. gnode += getAttribute( bufferGeometry.attributes.uv2, uvName, [ 'S', 'T' ], 'float' );
  165. triangleInputs += `<input semantic="TEXCOORD" source="#${uvName}" offset="0" set="1" />`;
  166. } // serialize colors
  167. if ( 'color' in bufferGeometry.attributes ) {
  168. // colors are always written as floats
  169. const colName = `${meshid}-color`;
  170. gnode += getAttribute( bufferGeometry.attributes.color, colName, [ 'R', 'G', 'B' ], 'float', true );
  171. triangleInputs += `<input semantic="COLOR" source="#${colName}" offset="0" />`;
  172. }
  173. let indexArray = null;
  174. if ( bufferGeometry.index ) {
  175. indexArray = attrBufferToArray( bufferGeometry.index );
  176. } else {
  177. indexArray = new Array( indexCount );
  178. for ( let i = 0, l = indexArray.length; i < l; i ++ ) indexArray[ i ] = i;
  179. }
  180. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  181. const group = groups[ i ];
  182. const subarr = subArray( indexArray, group.start, group.count );
  183. const polycount = subarr.length / 3;
  184. gnode += `<triangles material="MESH_MATERIAL_${group.materialIndex}" count="${polycount}">`;
  185. gnode += triangleInputs;
  186. gnode += `<p>${subarr.join( ' ' )}</p>`;
  187. gnode += '</triangles>';
  188. }
  189. gnode += '</mesh></geometry>';
  190. libraryGeometries.push( gnode );
  191. info = {
  192. meshid: meshid,
  193. bufferGeometry: bufferGeometry
  194. };
  195. geometryInfo.set( g, info );
  196. }
  197. return info;
  198. } // Process the given texture into the image library
  199. // Returns the image library
  200. function processTexture( tex ) {
  201. let texid = imageMap.get( tex );
  202. if ( texid == null ) {
  203. texid = `image-${libraryImages.length + 1}`;
  204. const ext = 'png';
  205. const name = tex.name || texid;
  206. let 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. } // Process the given material into the material and effect libraries
  226. // Returns the material id
  227. function processMaterial( m ) {
  228. let matid = materialMap.get( m );
  229. if ( matid == null ) {
  230. matid = `Mat${libraryEffects.length + 1}`;
  231. let type = 'phong';
  232. if ( m.isMeshLambertMaterial === true ) {
  233. type = 'lambert';
  234. } else if ( m.isMeshBasicMaterial === true ) {
  235. type = 'constant';
  236. if ( m.map !== null ) {
  237. // The Collada spec does not support diffuse texture maps with the
  238. // constant shader type.
  239. // mrdoob/three.js#15469
  240. console.warn( 'ColladaExporter: Texture maps not supported with THREE.MeshBasicMaterial.' );
  241. }
  242. }
  243. const emissive = m.emissive ? m.emissive : new THREE.Color( 0, 0, 0 );
  244. const diffuse = m.color ? m.color : new THREE.Color( 0, 0, 0 );
  245. const specular = m.specular ? m.specular : new THREE.Color( 1, 1, 1 );
  246. const shininess = m.shininess || 0;
  247. const reflectivity = m.reflectivity || 0;
  248. emissive.convertLinearToSRGB();
  249. specular.convertLinearToSRGB();
  250. diffuse.convertLinearToSRGB(); // Do not export and alpha map for the reasons mentioned in issue (#13792)
  251. // in three.js alpha maps are black and white, but collada expects the alpha
  252. // channel to specify the transparency
  253. let transparencyNode = '';
  254. if ( m.transparent === true ) {
  255. transparencyNode += '<transparent>' + ( m.map ? '<texture texture="diffuse-sampler"></texture>' : '<float>1</float>' ) + '</transparent>';
  256. if ( m.opacity < 1 ) {
  257. transparencyNode += `<transparency><float>${m.opacity}</float></transparency>`;
  258. }
  259. }
  260. 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>`;
  261. 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>';
  262. const materialName = m.name ? ` name="${m.name}"` : '';
  263. const materialNode = `<material id="${matid}"${materialName}><instance_effect url="#${matid}-effect" /></material>`;
  264. libraryMaterials.push( materialNode );
  265. libraryEffects.push( effectnode );
  266. materialMap.set( m, matid );
  267. }
  268. return matid;
  269. } // Recursively process the object into a scene
  270. function processObject( o ) {
  271. let node = `<node name="${o.name}">`;
  272. node += getTransform( o );
  273. if ( o.isMesh === true && o.geometry !== null ) {
  274. // function returns the id associated with the mesh and a "BufferGeometry" version
  275. // of the geometry in case it's not a geometry.
  276. const geomInfo = processGeometry( o.geometry );
  277. const meshid = geomInfo.meshid;
  278. const geometry = geomInfo.bufferGeometry; // ids of the materials to bind to the geometry
  279. let matids = null;
  280. let matidsArray; // get a list of materials to bind to the sub groups of the geometry.
  281. // If the amount of subgroups is greater than the materials, than reuse
  282. // the materials.
  283. const mat = o.material || new THREE.MeshBasicMaterial();
  284. const materials = Array.isArray( mat ) ? mat : [ mat ];
  285. if ( geometry.groups.length > materials.length ) {
  286. matidsArray = new Array( geometry.groups.length );
  287. } else {
  288. matidsArray = new Array( materials.length );
  289. }
  290. matids = matidsArray.fill().map( ( v, i ) => processMaterial( materials[ i % materials.length ] ) );
  291. 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>';
  292. }
  293. o.children.forEach( c => node += processObject( c ) );
  294. node += '</node>';
  295. return node;
  296. }
  297. const geometryInfo = new WeakMap();
  298. const materialMap = new WeakMap();
  299. const imageMap = new WeakMap();
  300. const textures = [];
  301. const libraryImages = [];
  302. const libraryGeometries = [];
  303. const libraryEffects = [];
  304. const libraryMaterials = [];
  305. const libraryVisualScenes = processObject( object );
  306. const specLink = version === '1.4.1' ? 'http://www.collada.org/2005/11/COLLADASchema' : 'https://www.khronos.org/collada/';
  307. 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>';
  308. dae += `<library_images>${libraryImages.join( '' )}</library_images>`;
  309. dae += `<library_effects>${libraryEffects.join( '' )}</library_effects>`;
  310. dae += `<library_materials>${libraryMaterials.join( '' )}</library_materials>`;
  311. dae += `<library_geometries>${libraryGeometries.join( '' )}</library_geometries>`;
  312. dae += `<library_visual_scenes><visual_scene id="Scene" name="scene">${libraryVisualScenes}</visual_scene></library_visual_scenes>`;
  313. dae += '<scene><instance_visual_scene url="#Scene"/></scene>';
  314. dae += '</COLLADA>';
  315. const res = {
  316. data: format( dae ),
  317. textures
  318. };
  319. if ( typeof onDone === 'function' ) {
  320. requestAnimationFrame( () => onDone( res ) );
  321. }
  322. return res;
  323. }
  324. }
  325. THREE.ColladaExporter = ColladaExporter;
  326. } )();