PLYLoader.js 17 KB

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