PCDLoader.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. import {
  2. BufferGeometry,
  3. Color,
  4. FileLoader,
  5. Float32BufferAttribute,
  6. Int32BufferAttribute,
  7. Loader,
  8. Points,
  9. PointsMaterial,
  10. SRGBColorSpace
  11. } from 'three';
  12. /**
  13. * A loader for the Point Cloud Data (PCD) format.
  14. *
  15. * PCDLoader supports ASCII and (compressed) binary files as well as the following PCD fields:
  16. * - x y z
  17. * - rgb
  18. * - normal_x normal_y normal_z
  19. * - intensity
  20. * - label
  21. *
  22. * ```js
  23. * const loader = new PCDLoader();
  24. *
  25. * const points = await loader.loadAsync( './models/pcd/binary/Zaghetto.pcd' );
  26. * points.geometry.center(); // optional
  27. * points.geometry.rotateX( Math.PI ); // optional
  28. * scene.add( points );
  29. * ```
  30. *
  31. * @augments Loader
  32. * @three_import import { PCDLoader } from 'three/addons/loaders/PCDLoader.js';
  33. */
  34. class PCDLoader extends Loader {
  35. /**
  36. * Constructs a new PCD loader.
  37. *
  38. * @param {LoadingManager} [manager] - The loading manager.
  39. */
  40. constructor( manager ) {
  41. super( manager );
  42. /**
  43. * Whether to use little Endian or not.
  44. *
  45. * @type {boolean}
  46. * @default true
  47. */
  48. this.littleEndian = true;
  49. }
  50. /**
  51. * Starts loading from the given URL and passes the loaded PCD asset
  52. * to the `onLoad()` callback.
  53. *
  54. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  55. * @param {function(Points)} onLoad - Executed when the loading process has been finished.
  56. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  57. * @param {onErrorCallback} onError - Executed when errors occur.
  58. */
  59. load( url, onLoad, onProgress, onError ) {
  60. const scope = this;
  61. const loader = new FileLoader( scope.manager );
  62. loader.setPath( scope.path );
  63. loader.setResponseType( 'arraybuffer' );
  64. loader.setRequestHeader( scope.requestHeader );
  65. loader.setWithCredentials( scope.withCredentials );
  66. loader.load( url, function ( data ) {
  67. try {
  68. onLoad( scope.parse( data ) );
  69. } catch ( e ) {
  70. if ( onError ) {
  71. onError( e );
  72. } else {
  73. console.error( e );
  74. }
  75. scope.manager.itemError( url );
  76. }
  77. }, onProgress, onError );
  78. }
  79. /**
  80. * Parses the given PCD data and returns a point cloud.
  81. *
  82. * @param {ArrayBuffer} data - The raw PCD data as an array buffer.
  83. * @return {Points} The parsed point cloud.
  84. */
  85. parse( data ) {
  86. // from https://gitlab.com/taketwo/three-pcd-loader/blob/master/decompress-lzf.js
  87. function decompressLZF( inData, outLength ) {
  88. const inLength = inData.length;
  89. const outData = new Uint8Array( outLength );
  90. let inPtr = 0;
  91. let outPtr = 0;
  92. let ctrl;
  93. let len;
  94. let ref;
  95. do {
  96. ctrl = inData[ inPtr ++ ];
  97. if ( ctrl < ( 1 << 5 ) ) {
  98. ctrl ++;
  99. if ( outPtr + ctrl > outLength ) throw new Error( 'Output buffer is not large enough' );
  100. if ( inPtr + ctrl > inLength ) throw new Error( 'Invalid compressed data' );
  101. do {
  102. outData[ outPtr ++ ] = inData[ inPtr ++ ];
  103. } while ( -- ctrl );
  104. } else {
  105. len = ctrl >> 5;
  106. ref = outPtr - ( ( ctrl & 0x1f ) << 8 ) - 1;
  107. if ( inPtr >= inLength ) throw new Error( 'Invalid compressed data' );
  108. if ( len === 7 ) {
  109. len += inData[ inPtr ++ ];
  110. if ( inPtr >= inLength ) throw new Error( 'Invalid compressed data' );
  111. }
  112. ref -= inData[ inPtr ++ ];
  113. if ( outPtr + len + 2 > outLength ) throw new Error( 'Output buffer is not large enough' );
  114. if ( ref < 0 ) throw new Error( 'Invalid compressed data' );
  115. if ( ref >= outPtr ) throw new Error( 'Invalid compressed data' );
  116. do {
  117. outData[ outPtr ++ ] = outData[ ref ++ ];
  118. } while ( -- len + 2 );
  119. }
  120. } while ( inPtr < inLength );
  121. return outData;
  122. }
  123. function parseHeader( data ) {
  124. const PCDheader = {};
  125. const result1 = data.search( /[\r\n]DATA\s(\S*)\s/i );
  126. const result2 = /[\r\n]DATA\s(\S*)\s/i.exec( data.slice( result1 - 1 ) );
  127. PCDheader.data = result2[ 1 ];
  128. PCDheader.headerLen = result2[ 0 ].length + result1;
  129. PCDheader.str = data.slice( 0, PCDheader.headerLen );
  130. // remove comments
  131. PCDheader.str = PCDheader.str.replace( /#.*/gi, '' );
  132. // parse
  133. PCDheader.version = /^VERSION (.*)/im.exec( PCDheader.str );
  134. PCDheader.fields = /^FIELDS (.*)/im.exec( PCDheader.str );
  135. PCDheader.size = /^SIZE (.*)/im.exec( PCDheader.str );
  136. PCDheader.type = /^TYPE (.*)/im.exec( PCDheader.str );
  137. PCDheader.count = /^COUNT (.*)/im.exec( PCDheader.str );
  138. PCDheader.width = /^WIDTH (.*)/im.exec( PCDheader.str );
  139. PCDheader.height = /^HEIGHT (.*)/im.exec( PCDheader.str );
  140. PCDheader.viewpoint = /^VIEWPOINT (.*)/im.exec( PCDheader.str );
  141. PCDheader.points = /^POINTS (.*)/im.exec( PCDheader.str );
  142. // evaluate
  143. if ( PCDheader.version !== null )
  144. PCDheader.version = parseFloat( PCDheader.version[ 1 ] );
  145. PCDheader.fields = ( PCDheader.fields !== null ) ? PCDheader.fields[ 1 ].split( ' ' ) : [];
  146. if ( PCDheader.type !== null )
  147. PCDheader.type = PCDheader.type[ 1 ].split( ' ' );
  148. if ( PCDheader.width !== null )
  149. PCDheader.width = parseInt( PCDheader.width[ 1 ] );
  150. if ( PCDheader.height !== null )
  151. PCDheader.height = parseInt( PCDheader.height[ 1 ] );
  152. if ( PCDheader.viewpoint !== null )
  153. PCDheader.viewpoint = PCDheader.viewpoint[ 1 ];
  154. if ( PCDheader.points !== null )
  155. PCDheader.points = parseInt( PCDheader.points[ 1 ], 10 );
  156. if ( PCDheader.points === null )
  157. PCDheader.points = PCDheader.width * PCDheader.height;
  158. if ( PCDheader.size !== null ) {
  159. PCDheader.size = PCDheader.size[ 1 ].split( ' ' ).map( function ( x ) {
  160. return parseInt( x, 10 );
  161. } );
  162. }
  163. if ( PCDheader.count !== null ) {
  164. PCDheader.count = PCDheader.count[ 1 ].split( ' ' ).map( function ( x ) {
  165. return parseInt( x, 10 );
  166. } );
  167. } else {
  168. PCDheader.count = [];
  169. for ( let i = 0, l = PCDheader.fields.length; i < l; i ++ ) {
  170. PCDheader.count.push( 1 );
  171. }
  172. }
  173. PCDheader.offset = {};
  174. let sizeSum = 0;
  175. for ( let i = 0, l = PCDheader.fields.length; i < l; i ++ ) {
  176. if ( PCDheader.data === 'ascii' ) {
  177. PCDheader.offset[ PCDheader.fields[ i ] ] = i;
  178. } else {
  179. PCDheader.offset[ PCDheader.fields[ i ] ] = sizeSum;
  180. sizeSum += PCDheader.size[ i ] * PCDheader.count[ i ];
  181. }
  182. }
  183. // for binary only
  184. PCDheader.rowSize = sizeSum;
  185. return PCDheader;
  186. }
  187. const textData = new TextDecoder().decode( data );
  188. // parse header (always ascii format)
  189. const PCDheader = parseHeader( textData );
  190. // parse data
  191. const position = [];
  192. const normal = [];
  193. const color = [];
  194. const intensity = [];
  195. const label = [];
  196. const c = new Color();
  197. // ascii
  198. if ( PCDheader.data === 'ascii' ) {
  199. const offset = PCDheader.offset;
  200. const pcdData = textData.slice( PCDheader.headerLen );
  201. const lines = pcdData.split( '\n' );
  202. for ( let i = 0, l = lines.length; i < l; i ++ ) {
  203. if ( lines[ i ] === '' ) continue;
  204. const line = lines[ i ].split( ' ' );
  205. if ( offset.x !== undefined ) {
  206. position.push( parseFloat( line[ offset.x ] ) );
  207. position.push( parseFloat( line[ offset.y ] ) );
  208. position.push( parseFloat( line[ offset.z ] ) );
  209. }
  210. if ( offset.rgb !== undefined ) {
  211. const rgb_field_index = PCDheader.fields.findIndex( ( field ) => field === 'rgb' );
  212. const rgb_type = PCDheader.type[ rgb_field_index ];
  213. const float = parseFloat( line[ offset.rgb ] );
  214. let rgb = float;
  215. if ( rgb_type === 'F' ) {
  216. // treat float values as int
  217. // https://github.com/daavoo/pyntcloud/pull/204/commits/7b4205e64d5ed09abe708b2e91b615690c24d518
  218. const farr = new Float32Array( 1 );
  219. farr[ 0 ] = float;
  220. rgb = new Int32Array( farr.buffer )[ 0 ];
  221. }
  222. const r = ( ( rgb >> 16 ) & 0x0000ff ) / 255;
  223. const g = ( ( rgb >> 8 ) & 0x0000ff ) / 255;
  224. const b = ( ( rgb >> 0 ) & 0x0000ff ) / 255;
  225. c.setRGB( r, g, b, SRGBColorSpace );
  226. color.push( c.r, c.g, c.b );
  227. }
  228. if ( offset.normal_x !== undefined ) {
  229. normal.push( parseFloat( line[ offset.normal_x ] ) );
  230. normal.push( parseFloat( line[ offset.normal_y ] ) );
  231. normal.push( parseFloat( line[ offset.normal_z ] ) );
  232. }
  233. if ( offset.intensity !== undefined ) {
  234. intensity.push( parseFloat( line[ offset.intensity ] ) );
  235. }
  236. if ( offset.label !== undefined ) {
  237. label.push( parseInt( line[ offset.label ] ) );
  238. }
  239. }
  240. }
  241. // binary-compressed
  242. // normally data in PCD files are organized as array of structures: XYZRGBXYZRGB
  243. // binary compressed PCD files organize their data as structure of arrays: XXYYZZRGBRGB
  244. // that requires a totally different parsing approach compared to non-compressed data
  245. if ( PCDheader.data === 'binary_compressed' ) {
  246. const sizes = new Uint32Array( data.slice( PCDheader.headerLen, PCDheader.headerLen + 8 ) );
  247. const compressedSize = sizes[ 0 ];
  248. const decompressedSize = sizes[ 1 ];
  249. const decompressed = decompressLZF( new Uint8Array( data, PCDheader.headerLen + 8, compressedSize ), decompressedSize );
  250. const dataview = new DataView( decompressed.buffer );
  251. const offset = PCDheader.offset;
  252. for ( let i = 0; i < PCDheader.points; i ++ ) {
  253. if ( offset.x !== undefined ) {
  254. const xIndex = PCDheader.fields.indexOf( 'x' );
  255. const yIndex = PCDheader.fields.indexOf( 'y' );
  256. const zIndex = PCDheader.fields.indexOf( 'z' );
  257. position.push( dataview.getFloat32( ( PCDheader.points * offset.x ) + PCDheader.size[ xIndex ] * i, this.littleEndian ) );
  258. position.push( dataview.getFloat32( ( PCDheader.points * offset.y ) + PCDheader.size[ yIndex ] * i, this.littleEndian ) );
  259. position.push( dataview.getFloat32( ( PCDheader.points * offset.z ) + PCDheader.size[ zIndex ] * i, this.littleEndian ) );
  260. }
  261. if ( offset.rgb !== undefined ) {
  262. const rgbIndex = PCDheader.fields.indexOf( 'rgb' );
  263. const r = dataview.getUint8( ( PCDheader.points * offset.rgb ) + PCDheader.size[ rgbIndex ] * i + 2 ) / 255.0;
  264. const g = dataview.getUint8( ( PCDheader.points * offset.rgb ) + PCDheader.size[ rgbIndex ] * i + 1 ) / 255.0;
  265. const b = dataview.getUint8( ( PCDheader.points * offset.rgb ) + PCDheader.size[ rgbIndex ] * i + 0 ) / 255.0;
  266. c.setRGB( r, g, b, SRGBColorSpace );
  267. color.push( c.r, c.g, c.b );
  268. }
  269. if ( offset.normal_x !== undefined ) {
  270. const xIndex = PCDheader.fields.indexOf( 'normal_x' );
  271. const yIndex = PCDheader.fields.indexOf( 'normal_y' );
  272. const zIndex = PCDheader.fields.indexOf( 'normal_z' );
  273. normal.push( dataview.getFloat32( ( PCDheader.points * offset.normal_x ) + PCDheader.size[ xIndex ] * i, this.littleEndian ) );
  274. normal.push( dataview.getFloat32( ( PCDheader.points * offset.normal_y ) + PCDheader.size[ yIndex ] * i, this.littleEndian ) );
  275. normal.push( dataview.getFloat32( ( PCDheader.points * offset.normal_z ) + PCDheader.size[ zIndex ] * i, this.littleEndian ) );
  276. }
  277. if ( offset.intensity !== undefined ) {
  278. const intensityIndex = PCDheader.fields.indexOf( 'intensity' );
  279. intensity.push( dataview.getFloat32( ( PCDheader.points * offset.intensity ) + PCDheader.size[ intensityIndex ] * i, this.littleEndian ) );
  280. }
  281. if ( offset.label !== undefined ) {
  282. const labelIndex = PCDheader.fields.indexOf( 'label' );
  283. label.push( dataview.getInt32( ( PCDheader.points * offset.label ) + PCDheader.size[ labelIndex ] * i, this.littleEndian ) );
  284. }
  285. }
  286. }
  287. // binary
  288. if ( PCDheader.data === 'binary' ) {
  289. const dataview = new DataView( data, PCDheader.headerLen );
  290. const offset = PCDheader.offset;
  291. for ( let i = 0, row = 0; i < PCDheader.points; i ++, row += PCDheader.rowSize ) {
  292. if ( offset.x !== undefined ) {
  293. position.push( dataview.getFloat32( row + offset.x, this.littleEndian ) );
  294. position.push( dataview.getFloat32( row + offset.y, this.littleEndian ) );
  295. position.push( dataview.getFloat32( row + offset.z, this.littleEndian ) );
  296. }
  297. if ( offset.rgb !== undefined ) {
  298. const r = dataview.getUint8( row + offset.rgb + 2 ) / 255.0;
  299. const g = dataview.getUint8( row + offset.rgb + 1 ) / 255.0;
  300. const b = dataview.getUint8( row + offset.rgb + 0 ) / 255.0;
  301. c.setRGB( r, g, b, SRGBColorSpace );
  302. color.push( c.r, c.g, c.b );
  303. }
  304. if ( offset.normal_x !== undefined ) {
  305. normal.push( dataview.getFloat32( row + offset.normal_x, this.littleEndian ) );
  306. normal.push( dataview.getFloat32( row + offset.normal_y, this.littleEndian ) );
  307. normal.push( dataview.getFloat32( row + offset.normal_z, this.littleEndian ) );
  308. }
  309. if ( offset.intensity !== undefined ) {
  310. intensity.push( dataview.getFloat32( row + offset.intensity, this.littleEndian ) );
  311. }
  312. if ( offset.label !== undefined ) {
  313. label.push( dataview.getInt32( row + offset.label, this.littleEndian ) );
  314. }
  315. }
  316. }
  317. // build geometry
  318. const geometry = new BufferGeometry();
  319. if ( position.length > 0 ) geometry.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  320. if ( normal.length > 0 ) geometry.setAttribute( 'normal', new Float32BufferAttribute( normal, 3 ) );
  321. if ( color.length > 0 ) geometry.setAttribute( 'color', new Float32BufferAttribute( color, 3 ) );
  322. if ( intensity.length > 0 ) geometry.setAttribute( 'intensity', new Float32BufferAttribute( intensity, 1 ) );
  323. if ( label.length > 0 ) geometry.setAttribute( 'label', new Int32BufferAttribute( label, 1 ) );
  324. geometry.computeBoundingSphere();
  325. // build material
  326. const material = new PointsMaterial( { size: 0.005 } );
  327. if ( color.length > 0 ) {
  328. material.vertexColors = true;
  329. }
  330. // build point cloud
  331. return new Points( geometry, material );
  332. }
  333. }
  334. export { PCDLoader };