PLYExporter.js 13 KB

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