XYZLoader.js 1.9 KB

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