PLYLoader.js 16 KB

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