PLYLoader.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  1. import {
  2. BufferGeometry,
  3. FileLoader,
  4. BufferAttribute,
  5. Float32BufferAttribute,
  6. Int8BufferAttribute,
  7. Int16BufferAttribute,
  8. Int32BufferAttribute,
  9. Loader,
  10. Uint8BufferAttribute,
  11. Uint16BufferAttribute,
  12. Uint32BufferAttribute,
  13. Color,
  14. SRGBColorSpace
  15. } from 'three';
  16. const _color = new Color();
  17. /**
  18. * A loader for PLY the PLY format (known as the Polygon
  19. * File Format or the Stanford Triangle Format).
  20. *
  21. * Limitations:
  22. * - ASCII decoding assumes file is UTF-8.
  23. *
  24. * ```js
  25. * const loader = new PLYLoader();
  26. * const geometry = await loader.loadAsync( './models/ply/ascii/dolphins.ply' );
  27. * scene.add( new THREE.Mesh( geometry ) );
  28. * ```
  29. *
  30. * @augments Loader
  31. * @three_import import { PLYLoader } from 'three/addons/loaders/PLYLoader.js';
  32. */
  33. class PLYLoader extends Loader {
  34. /**
  35. * Constructs a new PLY loader.
  36. *
  37. * @param {LoadingManager} [manager] - The loading manager.
  38. */
  39. constructor( manager ) {
  40. super( manager );
  41. // internals
  42. this.propertyNameMapping = {};
  43. this.customPropertyMapping = {};
  44. }
  45. /**
  46. * Starts loading from the given URL and passes the loaded PLY asset
  47. * to the `onLoad()` callback.
  48. *
  49. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  50. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  51. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  52. * @param {onErrorCallback} onError - Executed when errors occur.
  53. */
  54. load( url, onLoad, onProgress, onError ) {
  55. const scope = this;
  56. const loader = new FileLoader( this.manager );
  57. loader.setPath( this.path );
  58. loader.setResponseType( 'arraybuffer' );
  59. loader.setRequestHeader( this.requestHeader );
  60. loader.setWithCredentials( this.withCredentials );
  61. loader.load( url, function ( text ) {
  62. try {
  63. onLoad( scope.parse( text ) );
  64. } catch ( e ) {
  65. if ( onError ) {
  66. onError( e );
  67. } else {
  68. console.error( e );
  69. }
  70. scope.manager.itemError( url );
  71. }
  72. }, onProgress, onError );
  73. }
  74. /**
  75. * Sets a property name mapping that maps default property names
  76. * to custom ones. For example, the following maps the properties
  77. * “diffuse_(red|green|blue)” in the file to standard color names.
  78. *
  79. * ```js
  80. * loader.setPropertyNameMapping( {
  81. * diffuse_red: 'red',
  82. * diffuse_green: 'green',
  83. * diffuse_blue: 'blue'
  84. * } );
  85. * ```
  86. *
  87. * @param {Object} mapping - The mapping dictionary.
  88. */
  89. setPropertyNameMapping( mapping ) {
  90. this.propertyNameMapping = mapping;
  91. }
  92. /**
  93. * Custom properties outside of the defaults for position, uv, normal
  94. * and color attributes can be added using the setCustomPropertyNameMapping method.
  95. * For example, the following maps the element properties “custom_property_a”
  96. * and “custom_property_b” to an attribute “customAttribute” with an item size of 2.
  97. * Attribute item sizes are set from the number of element properties in the property array.
  98. *
  99. * ```js
  100. * loader.setCustomPropertyNameMapping( {
  101. * customAttribute: ['custom_property_a', 'custom_property_b'],
  102. * } );
  103. * ```
  104. * @param {Object} mapping - The mapping dictionary.
  105. */
  106. setCustomPropertyNameMapping( mapping ) {
  107. this.customPropertyMapping = mapping;
  108. }
  109. /**
  110. * Parses the given PLY data and returns the resulting geometry.
  111. *
  112. * @param {ArrayBuffer} data - The raw PLY data as an array buffer.
  113. * @return {BufferGeometry} The parsed geometry.
  114. */
  115. parse( data ) {
  116. function parseHeader( data, headerLength = 0 ) {
  117. const patternHeader = /^ply([\s\S]*)end_header(\r\n|\r|\n)/;
  118. let headerText = '';
  119. const result = patternHeader.exec( data );
  120. if ( result !== null ) {
  121. headerText = result[ 1 ];
  122. }
  123. const header = {
  124. comments: [],
  125. elements: [],
  126. headerLength: headerLength,
  127. objInfo: ''
  128. };
  129. const lines = headerText.split( /\r\n|\r|\n/ );
  130. let currentElement;
  131. function make_ply_element_property( propertyValues, propertyNameMapping ) {
  132. const property = { type: propertyValues[ 0 ] };
  133. if ( property.type === 'list' ) {
  134. property.name = propertyValues[ 3 ];
  135. property.countType = propertyValues[ 1 ];
  136. property.itemType = propertyValues[ 2 ];
  137. } else {
  138. property.name = propertyValues[ 1 ];
  139. }
  140. if ( property.name in propertyNameMapping ) {
  141. property.name = propertyNameMapping[ property.name ];
  142. }
  143. return property;
  144. }
  145. for ( let i = 0; i < lines.length; i ++ ) {
  146. let line = lines[ i ];
  147. line = line.trim();
  148. if ( line === '' ) continue;
  149. const lineValues = line.split( /\s+/ );
  150. const lineType = lineValues.shift();
  151. line = lineValues.join( ' ' );
  152. switch ( lineType ) {
  153. case 'format':
  154. header.format = lineValues[ 0 ];
  155. header.version = lineValues[ 1 ];
  156. break;
  157. case 'comment':
  158. header.comments.push( line );
  159. break;
  160. case 'element':
  161. if ( currentElement !== undefined ) {
  162. header.elements.push( currentElement );
  163. }
  164. currentElement = {};
  165. currentElement.name = lineValues[ 0 ];
  166. currentElement.count = parseInt( lineValues[ 1 ] );
  167. currentElement.properties = [];
  168. break;
  169. case 'property':
  170. currentElement.properties.push( make_ply_element_property( lineValues, scope.propertyNameMapping ) );
  171. break;
  172. case 'obj_info':
  173. header.objInfo = line;
  174. break;
  175. default:
  176. console.log( 'unhandled', lineType, lineValues );
  177. }
  178. }
  179. if ( currentElement !== undefined ) {
  180. header.elements.push( currentElement );
  181. }
  182. return header;
  183. }
  184. function parseASCIINumber( n, type ) {
  185. switch ( type ) {
  186. case 'char': case 'uchar': case 'short': case 'ushort': case 'int': case 'uint':
  187. case 'int8': case 'uint8': case 'int16': case 'uint16': case 'int32': case 'uint32':
  188. return parseInt( n );
  189. case 'float': case 'double': case 'float32': case 'float64':
  190. return parseFloat( n );
  191. }
  192. }
  193. function parseASCIIElement( properties, tokens ) {
  194. const element = {};
  195. for ( let i = 0; i < properties.length; i ++ ) {
  196. if ( tokens.empty() ) return null;
  197. if ( properties[ i ].type === 'list' ) {
  198. const list = [];
  199. const n = parseASCIINumber( tokens.next(), properties[ i ].countType );
  200. for ( let j = 0; j < n; j ++ ) {
  201. if ( tokens.empty() ) return null;
  202. list.push( parseASCIINumber( tokens.next(), properties[ i ].itemType ) );
  203. }
  204. element[ properties[ i ].name ] = list;
  205. } else {
  206. element[ properties[ i ].name ] = parseASCIINumber( tokens.next(), properties[ i ].type );
  207. }
  208. }
  209. return element;
  210. }
  211. function createBuffer() {
  212. const buffer = {
  213. indices: [],
  214. vertices: [],
  215. normals: [],
  216. uvs: [],
  217. faceVertexUvs: [],
  218. colors: [],
  219. faceVertexColors: [],
  220. descriptors: {}
  221. };
  222. for ( const customProperty of Object.keys( scope.customPropertyMapping ) ) {
  223. buffer[ customProperty ] = [];
  224. }
  225. return buffer;
  226. }
  227. function getBufferAttributeClass( type ) {
  228. switch ( type ) {
  229. case 'int8': case 'char': return Int8BufferAttribute;
  230. case 'uint8': case 'uchar': return Uint8BufferAttribute;
  231. case 'int16': case 'short': return Int16BufferAttribute;
  232. case 'uint16': case 'ushort': return Uint16BufferAttribute;
  233. case 'int32': case 'int': return Int32BufferAttribute;
  234. case 'uint32': case 'uint': return Uint32BufferAttribute;
  235. case 'float32': case 'float': return Float32BufferAttribute;
  236. case 'float64': case 'double': return Float64BufferAttribute;
  237. }
  238. }
  239. function getColorScale( type ) {
  240. switch ( type ) {
  241. case 'uchar': case 'uint8': return 1 / 255;
  242. case 'ushort': case 'uint16': return 1 / 65535;
  243. case 'float': case 'float32':
  244. case 'double': case 'float64': return 1;
  245. default: return 1 / 255;
  246. }
  247. }
  248. function isFloatType( type ) {
  249. return type === 'float' || type === 'float32' || type === 'double' || type === 'float64';
  250. }
  251. function getAttributeDescriptor( properties ) {
  252. function findProperty( names ) {
  253. for ( const name of names ) {
  254. const property = properties.find( p => p.name === name );
  255. if ( property ) return property;
  256. }
  257. return null;
  258. }
  259. // property lookup
  260. const x = findProperty( [ 'x', 'px', 'posx' ] );
  261. const y = findProperty( [ 'y', 'py', 'posy' ] );
  262. const z = findProperty( [ 'z', 'pz', 'posz' ] );
  263. const nx = findProperty( [ 'nx', 'normalx' ] );
  264. const ny = findProperty( [ 'ny', 'normaly' ] );
  265. const nz = findProperty( [ 'nz', 'normalz' ] );
  266. const s = findProperty( [ 's', 'u', 'texture_u', 'tx' ] );
  267. const t = findProperty( [ 't', 'v', 'texture_v', 'ty' ] );
  268. const r = findProperty( [ 'red', 'diffuse_red', 'r', 'diffuse_r' ] );
  269. const g = findProperty( [ 'green', 'diffuse_green', 'g', 'diffuse_g' ] );
  270. const b = findProperty( [ 'blue', 'diffuse_blue', 'b', 'diffuse_b' ] );
  271. const texcoord = findProperty( [ 'texcoord' ] );
  272. // custom property lookup
  273. const custom = {};
  274. for ( const customAttr of Object.keys( scope.customPropertyMapping ) ) {
  275. const propNames = scope.customPropertyMapping[ customAttr ];
  276. const matched = propNames.map( name => properties.find( p => p.name === name ) );
  277. const types = matched.filter( p => p ).map( p => p.type );
  278. const uniform = types.length > 0 && types.every( type => type === types[ 0 ] );
  279. custom[ customAttr ] = {
  280. type: uniform ? types[ 0 ] : 'float32',
  281. usage: matched.every( p => p !== undefined ),
  282. };
  283. }
  284. // build descriptor
  285. return {
  286. position: {
  287. names: [ x ? x.name : 'x', y ? y.name : 'y', z ? z.name : 'z' ],
  288. type: x ? x.type : 'float32',
  289. usage: !! ( x && y && z ),
  290. },
  291. normal: {
  292. names: [ nx ? nx.name : 'nx', ny ? ny.name : 'ny', nz ? nz.name : 'nz' ],
  293. type: nx ? nx.type : 'float32',
  294. usage: !! ( nx && ny && nz ),
  295. },
  296. uv: {
  297. names: [ s ? s.name : 's', t ? t.name : 't' ],
  298. type: s ? s.type : 'float32',
  299. usage: !! ( s && t ),
  300. },
  301. texcoord: {
  302. type: texcoord ? texcoord.itemType : 'float32',
  303. usage: !! texcoord,
  304. },
  305. color: {
  306. names: [ r ? r.name : 'red', g ? g.name : 'green', b ? b.name : 'blue' ],
  307. type: r ? r.type : 'uchar',
  308. usage: !! ( r && g && b ),
  309. },
  310. custom: custom,
  311. };
  312. }
  313. function parseASCII( data, header ) {
  314. // PLY ascii format specification, as per http://en.wikipedia.org/wiki/PLY_(file_format)
  315. const buffer = createBuffer();
  316. const patternBody = /end_header\s+(\S[\s\S]*\S|\S)\s*$/;
  317. let body, matches;
  318. if ( ( matches = patternBody.exec( data ) ) !== null ) {
  319. body = matches[ 1 ].split( /\s+/ );
  320. } else {
  321. body = [ ];
  322. }
  323. const tokens = new ArrayStream( body );
  324. loop: for ( let i = 0; i < header.elements.length; i ++ ) {
  325. const elementDesc = header.elements[ i ];
  326. const attributeDescriptor = getAttributeDescriptor( elementDesc.properties );
  327. buffer.descriptors[ elementDesc.name ] = attributeDescriptor;
  328. for ( let j = 0; j < elementDesc.count; j ++ ) {
  329. const element = parseASCIIElement( elementDesc.properties, tokens );
  330. if ( ! element ) break loop;
  331. handleElement( buffer, elementDesc.name, element, attributeDescriptor );
  332. }
  333. }
  334. return postProcess( buffer );
  335. }
  336. function postProcess( buffer ) {
  337. let geometry = new BufferGeometry();
  338. const vertexDescriptor = buffer.descriptors.vertex;
  339. // mandatory buffer data
  340. if ( buffer.indices.length > 0 ) {
  341. geometry.setIndex( buffer.indices );
  342. }
  343. const PositionClass = getBufferAttributeClass( vertexDescriptor ? vertexDescriptor.position.type : 'float32' );
  344. geometry.setAttribute( 'position', new PositionClass( buffer.vertices, 3 ) );
  345. // optional buffer data
  346. if ( buffer.normals.length > 0 ) {
  347. const NormalClass = getBufferAttributeClass( vertexDescriptor.normal.type );
  348. geometry.setAttribute( 'normal', new NormalClass( buffer.normals, 3 ) );
  349. }
  350. if ( buffer.uvs.length > 0 ) {
  351. const UvClass = getBufferAttributeClass( vertexDescriptor.uv.type );
  352. geometry.setAttribute( 'uv', new UvClass( buffer.uvs, 2 ) );
  353. }
  354. if ( buffer.colors.length > 0 ) {
  355. const colorType = vertexDescriptor.color.type;
  356. const normalized = ! isFloatType( colorType );
  357. const ColorClass = getBufferAttributeClass( colorType );
  358. geometry.setAttribute( 'color', new ColorClass( buffer.colors, 3, normalized ) );
  359. }
  360. if ( buffer.faceVertexUvs.length > 0 || buffer.faceVertexColors.length > 0 ) {
  361. geometry = geometry.toNonIndexed();
  362. if ( buffer.faceVertexUvs.length > 0 ) {
  363. const UvClass = getBufferAttributeClass( buffer.descriptors.face.texcoord.type );
  364. geometry.setAttribute( 'uv', new UvClass( buffer.faceVertexUvs, 2 ) );
  365. }
  366. if ( buffer.faceVertexColors.length > 0 ) {
  367. const colorType = buffer.descriptors.face.color.type;
  368. const normalized = ! isFloatType( colorType );
  369. const ColorClass = getBufferAttributeClass( colorType );
  370. geometry.setAttribute( 'color', new ColorClass( buffer.faceVertexColors, 3, normalized ) );
  371. }
  372. }
  373. // custom buffer data
  374. for ( const customProperty of Object.keys( scope.customPropertyMapping ) ) {
  375. if ( buffer[ customProperty ].length > 0 ) {
  376. const CustomClass = getBufferAttributeClass( vertexDescriptor.custom[ customProperty ].type );
  377. geometry.setAttribute( customProperty, new CustomClass( buffer[ customProperty ], scope.customPropertyMapping[ customProperty ].length ) );
  378. }
  379. }
  380. geometry.computeBoundingSphere();
  381. return geometry;
  382. }
  383. function handleElement( buffer, elementName, element, attributeDescriptor ) {
  384. if ( elementName === 'vertex' ) {
  385. const { position, normal, uv, color } = attributeDescriptor;
  386. if ( position.usage ) {
  387. buffer.vertices.push(
  388. element[ position.names[ 0 ] ],
  389. element[ position.names[ 1 ] ],
  390. element[ position.names[ 2 ] ]
  391. );
  392. }
  393. if ( normal.usage ) {
  394. buffer.normals.push(
  395. element[ normal.names[ 0 ] ],
  396. element[ normal.names[ 1 ] ],
  397. element[ normal.names[ 2 ] ]
  398. );
  399. }
  400. if ( uv.usage ) {
  401. buffer.uvs.push(
  402. element[ uv.names[ 0 ] ],
  403. element[ uv.names[ 1 ] ]
  404. );
  405. }
  406. if ( color.usage ) {
  407. const scale = getColorScale( color.type );
  408. const isFloat = isFloatType( color.type );
  409. // convert to float for color space conversion
  410. _color.setRGB(
  411. element[ color.names[ 0 ] ] * scale,
  412. element[ color.names[ 1 ] ] * scale,
  413. element[ color.names[ 2 ] ] * scale,
  414. SRGBColorSpace
  415. );
  416. // convert back to original type
  417. const invScale = 1 / scale;
  418. buffer.colors.push(
  419. isFloat ? _color.r : Math.round( _color.r * invScale ),
  420. isFloat ? _color.g : Math.round( _color.g * invScale ),
  421. isFloat ? _color.b : Math.round( _color.b * invScale )
  422. );
  423. }
  424. for ( const customProperty of Object.keys( scope.customPropertyMapping ) ) {
  425. for ( const elementProperty of scope.customPropertyMapping[ customProperty ] ) {
  426. buffer[ customProperty ].push( element[ elementProperty ] );
  427. }
  428. }
  429. } else if ( elementName === 'face' ) {
  430. const vertex_indices = element.vertex_indices || element.vertex_index; // issue #9338
  431. const texcoord = element.texcoord;
  432. if ( vertex_indices.length === 3 ) {
  433. buffer.indices.push( vertex_indices[ 0 ], vertex_indices[ 1 ], vertex_indices[ 2 ] );
  434. if ( texcoord && texcoord.length === 6 ) {
  435. buffer.faceVertexUvs.push( texcoord[ 0 ], texcoord[ 1 ] );
  436. buffer.faceVertexUvs.push( texcoord[ 2 ], texcoord[ 3 ] );
  437. buffer.faceVertexUvs.push( texcoord[ 4 ], texcoord[ 5 ] );
  438. }
  439. } else if ( vertex_indices.length === 4 ) {
  440. buffer.indices.push( vertex_indices[ 0 ], vertex_indices[ 1 ], vertex_indices[ 3 ] );
  441. buffer.indices.push( vertex_indices[ 1 ], vertex_indices[ 2 ], vertex_indices[ 3 ] );
  442. }
  443. // face colors
  444. const { color } = attributeDescriptor;
  445. if ( color.usage ) {
  446. // convert to float for color space conversion
  447. const scale = getColorScale( color.type );
  448. _color.setRGB(
  449. element[ color.names[ 0 ] ] * scale,
  450. element[ color.names[ 1 ] ] * scale,
  451. element[ color.names[ 2 ] ] * scale,
  452. SRGBColorSpace
  453. );
  454. // convert back to original type
  455. const invScale = 1 / scale;
  456. const r = _color.r * invScale;
  457. const g = _color.g * invScale;
  458. const b = _color.b * invScale;
  459. buffer.faceVertexColors.push( r, g, b );
  460. buffer.faceVertexColors.push( r, g, b );
  461. buffer.faceVertexColors.push( r, g, b );
  462. }
  463. }
  464. }
  465. function binaryReadElement( at, properties ) {
  466. const element = {};
  467. let read = 0;
  468. for ( let i = 0; i < properties.length; i ++ ) {
  469. const property = properties[ i ];
  470. const valueReader = property.valueReader;
  471. if ( property.type === 'list' ) {
  472. const list = [];
  473. const n = property.countReader.read( at + read );
  474. read += property.countReader.size;
  475. for ( let j = 0; j < n; j ++ ) {
  476. list.push( valueReader.read( at + read ) );
  477. read += valueReader.size;
  478. }
  479. element[ property.name ] = list;
  480. } else {
  481. element[ property.name ] = valueReader.read( at + read );
  482. read += valueReader.size;
  483. }
  484. }
  485. return [ element, read ];
  486. }
  487. function setPropertyBinaryReaders( properties, body, little_endian ) {
  488. function getBinaryReader( dataview, type, little_endian ) {
  489. switch ( type ) {
  490. // correspondences for non-specific length types here match rply:
  491. case 'int8': case 'char': return { read: ( at ) => {
  492. return dataview.getInt8( at );
  493. }, size: 1 };
  494. case 'uint8': case 'uchar': return { read: ( at ) => {
  495. return dataview.getUint8( at );
  496. }, size: 1 };
  497. case 'int16': case 'short': return { read: ( at ) => {
  498. return dataview.getInt16( at, little_endian );
  499. }, size: 2 };
  500. case 'uint16': case 'ushort': return { read: ( at ) => {
  501. return dataview.getUint16( at, little_endian );
  502. }, size: 2 };
  503. case 'int32': case 'int': return { read: ( at ) => {
  504. return dataview.getInt32( at, little_endian );
  505. }, size: 4 };
  506. case 'uint32': case 'uint': return { read: ( at ) => {
  507. return dataview.getUint32( at, little_endian );
  508. }, size: 4 };
  509. case 'float32': case 'float': return { read: ( at ) => {
  510. return dataview.getFloat32( at, little_endian );
  511. }, size: 4 };
  512. case 'float64': case 'double': return { read: ( at ) => {
  513. return dataview.getFloat64( at, little_endian );
  514. }, size: 8 };
  515. }
  516. }
  517. for ( let i = 0, l = properties.length; i < l; i ++ ) {
  518. const property = properties[ i ];
  519. if ( property.type === 'list' ) {
  520. property.countReader = getBinaryReader( body, property.countType, little_endian );
  521. property.valueReader = getBinaryReader( body, property.itemType, little_endian );
  522. } else {
  523. property.valueReader = getBinaryReader( body, property.type, little_endian );
  524. }
  525. }
  526. }
  527. function parseBinary( data, header ) {
  528. const buffer = createBuffer();
  529. const little_endian = ( header.format === 'binary_little_endian' );
  530. const body = new DataView( data, header.headerLength );
  531. let result, loc = 0;
  532. for ( let currentElement = 0; currentElement < header.elements.length; currentElement ++ ) {
  533. const elementDesc = header.elements[ currentElement ];
  534. const properties = elementDesc.properties;
  535. const attributeDescriptor = getAttributeDescriptor( properties );
  536. buffer.descriptors[ elementDesc.name ] = attributeDescriptor;
  537. setPropertyBinaryReaders( properties, body, little_endian );
  538. for ( let currentElementCount = 0; currentElementCount < elementDesc.count; currentElementCount ++ ) {
  539. result = binaryReadElement( loc, properties );
  540. loc += result[ 1 ];
  541. const element = result[ 0 ];
  542. handleElement( buffer, elementDesc.name, element, attributeDescriptor );
  543. }
  544. }
  545. return postProcess( buffer );
  546. }
  547. function extractHeaderText( bytes ) {
  548. let i = 0;
  549. let cont = true;
  550. let line = '';
  551. const lines = [];
  552. const startLine = new TextDecoder().decode( bytes.subarray( 0, 5 ) );
  553. const hasCRNL = /^ply\r\n/.test( startLine );
  554. do {
  555. const c = String.fromCharCode( bytes[ i ++ ] );
  556. if ( c !== '\n' && c !== '\r' ) {
  557. line += c;
  558. } else {
  559. if ( line === 'end_header' ) cont = false;
  560. if ( line !== '' ) {
  561. lines.push( line );
  562. line = '';
  563. }
  564. }
  565. } while ( cont && i < bytes.length );
  566. // ascii section using \r\n as line endings
  567. if ( hasCRNL === true ) i ++;
  568. return { headerText: lines.join( '\r' ) + '\r', headerLength: i };
  569. }
  570. //
  571. let geometry;
  572. const scope = this;
  573. if ( data instanceof ArrayBuffer ) {
  574. const bytes = new Uint8Array( data );
  575. const { headerText, headerLength } = extractHeaderText( bytes );
  576. const header = parseHeader( headerText, headerLength );
  577. if ( header.format === 'ascii' ) {
  578. const text = new TextDecoder().decode( bytes );
  579. geometry = parseASCII( text, header );
  580. } else {
  581. geometry = parseBinary( data, header );
  582. }
  583. } else {
  584. geometry = parseASCII( data, parseHeader( data ) );
  585. }
  586. return geometry;
  587. }
  588. }
  589. class Float64BufferAttribute extends BufferAttribute {
  590. constructor( array, itemSize, normalized ) {
  591. super( new Float64Array( array ), itemSize, normalized );
  592. }
  593. }
  594. class ArrayStream {
  595. constructor( arr ) {
  596. this.arr = arr;
  597. this.i = 0;
  598. }
  599. empty() {
  600. return this.i >= this.arr.length;
  601. }
  602. next() {
  603. return this.arr[ this.i ++ ];
  604. }
  605. }
  606. export { PLYLoader };
粤ICP备19079148号