XYZLoader.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import {
  2. BufferGeometry,
  3. FileLoader,
  4. Float32BufferAttribute,
  5. Loader
  6. } from 'three';
  7. class XYZLoader extends Loader {
  8. load( url, onLoad, onProgress, onError ) {
  9. const scope = this;
  10. const loader = new FileLoader( this.manager );
  11. loader.setPath( this.path );
  12. loader.setRequestHeader( this.requestHeader );
  13. loader.setWithCredentials( this.withCredentials );
  14. loader.load( url, function ( text ) {
  15. try {
  16. onLoad( scope.parse( text ) );
  17. } catch ( e ) {
  18. if ( onError ) {
  19. onError( e );
  20. } else {
  21. console.error( e );
  22. }
  23. scope.manager.itemError( url );
  24. }
  25. }, onProgress, onError );
  26. }
  27. parse( text ) {
  28. const lines = text.split( '\n' );
  29. const vertices = [];
  30. const colors = [];
  31. for ( let line of lines ) {
  32. line = line.trim();
  33. if ( line.charAt( 0 ) === '#' ) continue; // skip comments
  34. const lineValues = line.split( /\s+/ );
  35. if ( lineValues.length === 3 ) {
  36. // XYZ
  37. vertices.push( parseFloat( lineValues[ 0 ] ) );
  38. vertices.push( parseFloat( lineValues[ 1 ] ) );
  39. vertices.push( parseFloat( lineValues[ 2 ] ) );
  40. }
  41. if ( lineValues.length === 6 ) {
  42. // XYZRGB
  43. vertices.push( parseFloat( lineValues[ 0 ] ) );
  44. vertices.push( parseFloat( lineValues[ 1 ] ) );
  45. vertices.push( parseFloat( lineValues[ 2 ] ) );
  46. colors.push( parseFloat( lineValues[ 3 ] ) / 255 );
  47. colors.push( parseFloat( lineValues[ 4 ] ) / 255 );
  48. colors.push( parseFloat( lineValues[ 5 ] ) / 255 );
  49. }
  50. }
  51. const geometry = new BufferGeometry();
  52. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  53. if ( colors.length > 0 ) {
  54. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  55. }
  56. return geometry;
  57. }
  58. }
  59. export { XYZLoader };