PLYExporter.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. import {
  2. Matrix3,
  3. Vector3,
  4. Color,
  5. ColorManagement,
  6. SRGBColorSpace
  7. } from 'three';
  8. /**
  9. * An exporter for PLY.
  10. *
  11. * PLY (Polygon or Stanford Triangle Format) is a file format for efficient delivery and
  12. * loading of simple, static 3D content in a dense format. Both binary and ascii formats are
  13. * supported. PLY can store vertex positions, colors, normals and uv coordinates. No textures
  14. * or texture references are saved.
  15. *
  16. * ```js
  17. * const exporter = new PLYExporter();
  18. * const data = exporter.parse( scene, options );
  19. * ```
  20. *
  21. * @three_import import { PLYExporter } from 'three/addons/exporters/PLYExporter.js';
  22. */
  23. class PLYExporter {
  24. /**
  25. * Parses the given 3D object and generates the PLY output.
  26. *
  27. * If the 3D object is composed of multiple children and geometry, they are merged into a single mesh in the file.
  28. *
  29. * @param {Object3D} object - The 3D object to export.
  30. * @param {PLYExporter~OnDone} onDone - A callback function that is executed when the export has finished.
  31. * @param {PLYExporter~Options} options - The export options.
  32. * @return {?string|ArrayBuffer} The exported PLY.
  33. */
  34. parse( object, onDone, options = {} ) {
  35. // reference https://github.com/gkjohnson/ply-exporter-js
  36. // Iterate over the valid meshes in the object
  37. function traverseMeshes( cb ) {
  38. object.traverse( function ( child ) {
  39. if ( child.isMesh === true || child.isPoints ) {
  40. const mesh = child;
  41. const geometry = mesh.geometry;
  42. if ( geometry.hasAttribute( 'position' ) === true ) {
  43. cb( mesh, geometry );
  44. }
  45. }
  46. } );
  47. }
  48. // Default options
  49. const defaultOptions = {
  50. binary: false,
  51. excludeAttributes: [], // normal, uv, color, index
  52. littleEndian: false
  53. };
  54. options = Object.assign( defaultOptions, options );
  55. const excludeAttributes = options.excludeAttributes;
  56. let includeIndices = true;
  57. let includeNormals = false;
  58. let includeColors = false;
  59. let includeUVs = false;
  60. // count the vertices, check which properties are used,
  61. // and cache the BufferGeometry
  62. let vertexCount = 0;
  63. let faceCount = 0;
  64. object.traverse( function ( child ) {
  65. if ( child.isMesh === true ) {
  66. const mesh = child;
  67. const geometry = mesh.geometry;
  68. const vertices = geometry.getAttribute( 'position' );
  69. const normals = geometry.getAttribute( 'normal' );
  70. const uvs = geometry.getAttribute( 'uv' );
  71. const colors = geometry.getAttribute( 'color' );
  72. const indices = geometry.getIndex();
  73. if ( vertices === undefined ) {
  74. return;
  75. }
  76. vertexCount += vertices.count;
  77. faceCount += indices ? indices.count / 3 : vertices.count / 3;
  78. if ( normals !== undefined ) includeNormals = true;
  79. if ( uvs !== undefined ) includeUVs = true;
  80. if ( colors !== undefined ) includeColors = true;
  81. } else if ( child.isPoints ) {
  82. const mesh = child;
  83. const geometry = mesh.geometry;
  84. const vertices = geometry.getAttribute( 'position' );
  85. const normals = geometry.getAttribute( 'normal' );
  86. const colors = geometry.getAttribute( 'color' );
  87. vertexCount += vertices.count;
  88. if ( normals !== undefined ) includeNormals = true;
  89. if ( colors !== undefined ) includeColors = true;
  90. includeIndices = false;
  91. }
  92. } );
  93. const tempColor = new Color();
  94. includeIndices = includeIndices && excludeAttributes.indexOf( 'index' ) === - 1;
  95. includeNormals = includeNormals && excludeAttributes.indexOf( 'normal' ) === - 1;
  96. includeColors = includeColors && excludeAttributes.indexOf( 'color' ) === - 1;
  97. includeUVs = includeUVs && excludeAttributes.indexOf( 'uv' ) === - 1;
  98. if ( includeIndices && faceCount !== Math.floor( faceCount ) ) {
  99. // point cloud meshes will not have an index array and may not have a
  100. // number of vertices that is divisible by 3 (and therefore representable
  101. // as triangles)
  102. console.error(
  103. 'PLYExporter: Failed to generate a valid PLY file with triangle indices because the ' +
  104. 'number of indices is not divisible by 3.'
  105. );
  106. return null;
  107. }
  108. const indexByteCount = 4;
  109. let header =
  110. 'ply\n' +
  111. `format ${ options.binary ? ( options.littleEndian ? 'binary_little_endian' : 'binary_big_endian' ) : 'ascii' } 1.0\n` +
  112. `element vertex ${vertexCount}\n` +
  113. // position
  114. 'property float x\n' +
  115. 'property float y\n' +
  116. 'property float z\n';
  117. if ( includeNormals === true ) {
  118. // normal
  119. header +=
  120. 'property float nx\n' +
  121. 'property float ny\n' +
  122. 'property float nz\n';
  123. }
  124. if ( includeUVs === true ) {
  125. // uvs
  126. header +=
  127. 'property float s\n' +
  128. 'property float t\n';
  129. }
  130. if ( includeColors === true ) {
  131. // colors
  132. header +=
  133. 'property uchar red\n' +
  134. 'property uchar green\n' +
  135. 'property uchar blue\n';
  136. }
  137. if ( includeIndices === true ) {
  138. // faces
  139. header +=
  140. `element face ${faceCount}\n` +
  141. 'property list uchar int vertex_index\n';
  142. }
  143. header += 'end_header\n';
  144. // Generate attribute data
  145. const vertex = new Vector3();
  146. const normalMatrixWorld = new Matrix3();
  147. let result = null;
  148. if ( options.binary === true ) {
  149. // Binary File Generation
  150. const headerBin = new TextEncoder().encode( header );
  151. // 3 position values at 4 bytes
  152. // 3 normal values at 4 bytes
  153. // 3 color channels with 1 byte
  154. // 2 uv values at 4 bytes
  155. const vertexListLength = vertexCount * ( 4 * 3 + ( includeNormals ? 4 * 3 : 0 ) + ( includeColors ? 3 : 0 ) + ( includeUVs ? 4 * 2 : 0 ) );
  156. // 1 byte shape descriptor
  157. // 3 vertex indices at ${indexByteCount} bytes
  158. const faceListLength = includeIndices ? faceCount * ( indexByteCount * 3 + 1 ) : 0;
  159. const output = new DataView( new ArrayBuffer( headerBin.length + vertexListLength + faceListLength ) );
  160. new Uint8Array( output.buffer ).set( headerBin, 0 );
  161. let vOffset = headerBin.length;
  162. let fOffset = headerBin.length + vertexListLength;
  163. let writtenVertices = 0;
  164. traverseMeshes( function ( mesh, geometry ) {
  165. const vertices = geometry.getAttribute( 'position' );
  166. const normals = geometry.getAttribute( 'normal' );
  167. const uvs = geometry.getAttribute( 'uv' );
  168. const colors = geometry.getAttribute( 'color' );
  169. const indices = geometry.getIndex();
  170. normalMatrixWorld.getNormalMatrix( mesh.matrixWorld );
  171. for ( let i = 0, l = vertices.count; i < l; i ++ ) {
  172. vertex.fromBufferAttribute( vertices, i );
  173. vertex.applyMatrix4( mesh.matrixWorld );
  174. // Position information
  175. output.setFloat32( vOffset, vertex.x, options.littleEndian );
  176. vOffset += 4;
  177. output.setFloat32( vOffset, vertex.y, options.littleEndian );
  178. vOffset += 4;
  179. output.setFloat32( vOffset, vertex.z, options.littleEndian );
  180. vOffset += 4;
  181. // Normal information
  182. if ( includeNormals === true ) {
  183. if ( normals != null ) {
  184. vertex.fromBufferAttribute( normals, i );
  185. vertex.applyMatrix3( normalMatrixWorld ).normalize();
  186. output.setFloat32( vOffset, vertex.x, options.littleEndian );
  187. vOffset += 4;
  188. output.setFloat32( vOffset, vertex.y, options.littleEndian );
  189. vOffset += 4;
  190. output.setFloat32( vOffset, vertex.z, options.littleEndian );
  191. vOffset += 4;
  192. } else {
  193. output.setFloat32( vOffset, 0, options.littleEndian );
  194. vOffset += 4;
  195. output.setFloat32( vOffset, 0, options.littleEndian );
  196. vOffset += 4;
  197. output.setFloat32( vOffset, 0, options.littleEndian );
  198. vOffset += 4;
  199. }
  200. }
  201. // UV information
  202. if ( includeUVs === true ) {
  203. if ( uvs != null ) {
  204. output.setFloat32( vOffset, uvs.getX( i ), options.littleEndian );
  205. vOffset += 4;
  206. output.setFloat32( vOffset, uvs.getY( i ), options.littleEndian );
  207. vOffset += 4;
  208. } else {
  209. output.setFloat32( vOffset, 0, options.littleEndian );
  210. vOffset += 4;
  211. output.setFloat32( vOffset, 0, options.littleEndian );
  212. vOffset += 4;
  213. }
  214. }
  215. // Color information
  216. if ( includeColors === true ) {
  217. if ( colors != null ) {
  218. tempColor.fromBufferAttribute( colors, i );
  219. ColorManagement.fromWorkingColorSpace( tempColor, SRGBColorSpace );
  220. output.setUint8( vOffset, Math.floor( tempColor.r * 255 ) );
  221. vOffset += 1;
  222. output.setUint8( vOffset, Math.floor( tempColor.g * 255 ) );
  223. vOffset += 1;
  224. output.setUint8( vOffset, Math.floor( tempColor.b * 255 ) );
  225. vOffset += 1;
  226. } else {
  227. output.setUint8( vOffset, 255 );
  228. vOffset += 1;
  229. output.setUint8( vOffset, 255 );
  230. vOffset += 1;
  231. output.setUint8( vOffset, 255 );
  232. vOffset += 1;
  233. }
  234. }
  235. }
  236. if ( includeIndices === true ) {
  237. // Create the face list
  238. if ( indices !== null ) {
  239. for ( let i = 0, l = indices.count; i < l; i += 3 ) {
  240. output.setUint8( fOffset, 3 );
  241. fOffset += 1;
  242. output.setUint32( fOffset, indices.getX( i + 0 ) + writtenVertices, options.littleEndian );
  243. fOffset += indexByteCount;
  244. output.setUint32( fOffset, indices.getX( i + 1 ) + writtenVertices, options.littleEndian );
  245. fOffset += indexByteCount;
  246. output.setUint32( fOffset, indices.getX( i + 2 ) + writtenVertices, options.littleEndian );
  247. fOffset += indexByteCount;
  248. }
  249. } else {
  250. for ( let i = 0, l = vertices.count; i < l; i += 3 ) {
  251. output.setUint8( fOffset, 3 );
  252. fOffset += 1;
  253. output.setUint32( fOffset, writtenVertices + i, options.littleEndian );
  254. fOffset += indexByteCount;
  255. output.setUint32( fOffset, writtenVertices + i + 1, options.littleEndian );
  256. fOffset += indexByteCount;
  257. output.setUint32( fOffset, writtenVertices + i + 2, options.littleEndian );
  258. fOffset += indexByteCount;
  259. }
  260. }
  261. }
  262. // Save the amount of verts we've already written so we can offset
  263. // the face index on the next mesh
  264. writtenVertices += vertices.count;
  265. } );
  266. result = output.buffer;
  267. } else {
  268. // Ascii File Generation
  269. // count the number of vertices
  270. let writtenVertices = 0;
  271. let vertexList = '';
  272. let faceList = '';
  273. traverseMeshes( function ( mesh, geometry ) {
  274. const vertices = geometry.getAttribute( 'position' );
  275. const normals = geometry.getAttribute( 'normal' );
  276. const uvs = geometry.getAttribute( 'uv' );
  277. const colors = geometry.getAttribute( 'color' );
  278. const indices = geometry.getIndex();
  279. normalMatrixWorld.getNormalMatrix( mesh.matrixWorld );
  280. // form each line
  281. for ( let i = 0, l = vertices.count; i < l; i ++ ) {
  282. vertex.fromBufferAttribute( vertices, i );
  283. vertex.applyMatrix4( mesh.matrixWorld );
  284. // Position information
  285. let line =
  286. vertex.x + ' ' +
  287. vertex.y + ' ' +
  288. vertex.z;
  289. // Normal information
  290. if ( includeNormals === true ) {
  291. if ( normals != null ) {
  292. vertex.fromBufferAttribute( normals, i );
  293. vertex.applyMatrix3( normalMatrixWorld ).normalize();
  294. line += ' ' +
  295. vertex.x + ' ' +
  296. vertex.y + ' ' +
  297. vertex.z;
  298. } else {
  299. line += ' 0 0 0';
  300. }
  301. }
  302. // UV information
  303. if ( includeUVs === true ) {
  304. if ( uvs != null ) {
  305. line += ' ' +
  306. uvs.getX( i ) + ' ' +
  307. uvs.getY( i );
  308. } else {
  309. line += ' 0 0';
  310. }
  311. }
  312. // Color information
  313. if ( includeColors === true ) {
  314. if ( colors != null ) {
  315. tempColor.fromBufferAttribute( colors, i );
  316. ColorManagement.fromWorkingColorSpace( tempColor, SRGBColorSpace );
  317. line += ' ' +
  318. Math.floor( tempColor.r * 255 ) + ' ' +
  319. Math.floor( tempColor.g * 255 ) + ' ' +
  320. Math.floor( tempColor.b * 255 );
  321. } else {
  322. line += ' 255 255 255';
  323. }
  324. }
  325. vertexList += line + '\n';
  326. }
  327. // Create the face list
  328. if ( includeIndices === true ) {
  329. if ( indices !== null ) {
  330. for ( let i = 0, l = indices.count; i < l; i += 3 ) {
  331. faceList += `3 ${ indices.getX( i + 0 ) + writtenVertices }`;
  332. faceList += ` ${ indices.getX( i + 1 ) + writtenVertices }`;
  333. faceList += ` ${ indices.getX( i + 2 ) + writtenVertices }\n`;
  334. }
  335. } else {
  336. for ( let i = 0, l = vertices.count; i < l; i += 3 ) {
  337. faceList += `3 ${ writtenVertices + i } ${ writtenVertices + i + 1 } ${ writtenVertices + i + 2 }\n`;
  338. }
  339. }
  340. faceCount += indices ? indices.count / 3 : vertices.count / 3;
  341. }
  342. writtenVertices += vertices.count;
  343. } );
  344. result = `${ header }${vertexList}${ includeIndices ? `${faceList}\n` : '\n' }`;
  345. }
  346. if ( typeof onDone === 'function' ) requestAnimationFrame( () => onDone( result ) );
  347. return result;
  348. }
  349. }
  350. /**
  351. * Export options of `PLYExporter`.
  352. *
  353. * @typedef {Object} PLYExporter~Options
  354. * @property {boolean} [binary=false] - Whether to export in binary format or ASCII.
  355. * @property {Array<string>} [excludeAttributes] - Which properties to explicitly exclude from
  356. * the exported PLY file. Valid values are `'color'`, `'normal'`, `'uv'`, and `'index'`. If triangle
  357. * indices are excluded, then a point cloud is exported.
  358. * @property {boolean} [littleEndian=false] - Whether the binary export uses little or big endian.
  359. **/
  360. /**
  361. * onDone callback of `PLYExporter`.
  362. *
  363. * @callback PLYExporter~OnDone
  364. * @param {string|ArrayBuffer} result - The generated PLY ascii or binary.
  365. */
  366. export { PLYExporter };